Node.js: express + MySQL + Vue realizes image upload

        Some time ago, I made a small project with Node.js: express + MySQL + Vue + element components, and recorded the implementation of image upload.

        There are two ways to store images in the database:

                1. Store the picture in the database as a binary stream (the database is easy to move and is relatively safe, but the consumption of database space is large and the access will be relatively slow)

                2. Store the storage address of the picture in the database

        The second type is mainly introduced.

1. Store the picture in the database as a binary stream

        Convert the image to base64 format, and use the MEDIUMTEXT type as the data type.

         Or convert the picture to a Blob type saved in the database.

Second, store the storage address of the picture in the database.

1. Write the interface url

        A middleware, Multer, will be used to process  multipart/form-data type of form data, which is mainly used for uploading files: multer/README-zh-cn.md at master expressjs/multer GitHub

        Multer will add a body object and a file or files object to the request object. The body object contains the text field information of the form, and the file object contains the file information uploaded by the object form.

(The two folders router and router_handle mean that the path and execution method are separated to facilitate management. For details, please refer to   Node.js: express + MySQL using _express mysql_ hair loss type player's blog - CSDN blog )

Files under router

//引入multer
const multer = require('multer')
//磁盘存储引擎,可以控制文件的存储,省略的话这些文件会保存在内存中,不会写入磁盘
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        //控制文件的存储路径
        cb(null, 'image/avatar')
    },
    filename: function (req, file, cb) {
        //定义上传文件存储时的文件名
        cb(null, file.originalname)
    }
})
const upload = multer({ storage: storage })
//接受单文件上传
router.post('/update/avatar', upload.single('avatar'), userInfo_handler.updateAvatar)

        First introduce multer, configure the storage address and file name of the image, if omitted, the uploaded file will be saved in the memory and will not be written to the disk. Before uploading, create a folder in the root directory of the project to receive the uploaded file , For example, the storage path of the defined file in my code is cb(null, 'image/avatar'), and an image folder should be created under the directory, and an avatar folder should be created under the image folder.

        The file name when defining file storage generally uses timestamp as the file name to prevent duplication of uploaded files (I did not use timestamp here). 

        upload.single('avatar') indicates that a single file upload is accepted, and avatar represents the parameter field when uploading a file. For multiple file uploads  .array(fieldname[, maxCount]), maxCount is used to limit the maximum number of uploads.

The processing function under the router_handler file

exports.updateAvatar = (req, res) => {
    // 定义更新头像的sql
    const sql = 'update users set avatar=? where id=?;'
    // console.log(req);
    // console.log(req.body.id)
    // console.log(req.file);
    // console.log(req.file.destination);
    const avatarUrl = `http://127.0.0.1:3007/${req.file.destination.split('/')[1]}/${req.file.originalname}`
    // console.log(avatarUrl);
    // 执行sql语句
    db.query(sql, [avatarUrl, req.body.id], (err, results) => {
        // sql语句执行错误
        if(err) return res.cc(err)
        // sql语句执行成功,但影响的条数部位1属于执行失败
        if(results.affectedRows !== 1) return res.cc('更换头像失败!')
        // 更换头像成功
        res.cc('更换头像成功!', 0)
    })
}

The returned request

 

        At this time, use req.file to get the uploaded picture information, and req.body to get other uploaded data.

        Then process the image path, and the image path is processed according to the actual situation of your project. Finally, execute the sql statement and store it in the database.

        The interface is processed.

        If you want to access the picture through the path in the browser, you need to add it to the app.js file

app.use(express.static('image'))

        Convert the entire image folder to static files.

2. Write front-end code

        The front-end code uses the element component as an example. Use the components uploaded in element. Several of these properties are more important.

         action is the URL of the request. If the interface you write needs to send a token, you need to configure headers. data is an additional parameter in the request except for the image file. name is the field for uploading the image file. This field must be the same as the field when defining the url Be consistent, it is the following field.

         Then re-request the data in the database and display the picture on the page.

after uploading

Where to save the picture

 

in the database 

 This path can be accessed directly in the browser

  

        You can go to the link below to get the code in the article.

        Link: https://pan.baidu.com/s/1t7bX0Nv3kggyf7IFzEffcA Extraction code: 0000

Guess you like

Origin blog.csdn.net/h360583690/article/details/131033991