Renaming an uploaded file using Multer doesn't work (Express.js)

后端 未结 6 1703
孤独总比滥情好
孤独总比滥情好 2021-02-07 20:43

I\'m trying to upload a file from a HTML form using Express.js and Multer. I\'ve managed to save the file to the desired location (a folder named uploads).

Howe

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-07 21:26

    I know this post is dated. I want to contribute to those who may arrive later. Below is a full functional server script to handle multiple uploaded pictures with random saved pictures names and file extension.

    var express = require("express");
    var multer = require("multer");
    var app = express();
    var path = require("path");
    var uuid = require("uuid");
    
    // Allow cross origin resource sharing (CORS) within our application
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    });
    
    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, 'uploadedimages/')
      },
      filename: function (req, file, cb) {
        cb(null, uuid.v4() + path.extname(file.originalname));
      }
    })
    
    var upload = multer({ storage: storage })
    
    // "files" should be the same name as what's coming from the field name on the client side.
    app.post("/upload", upload.array("files", 12), function(req, res) {
        res.send(req.files);
        console.log("files = ", req.files);
    });
    
    var server = app.listen(3000, function() {
        console.log("Listening on port %s...", server.address().port);
    });
    

提交回复
热议问题