简体   繁体   English

无法在multer中更改目的地

[英]Can't change destination in multer

When i upload my form (which just contains an image), the image goes in the root folder, but I would like it to go to /public/images. 当我上传表单(仅包含图像)时,图像进入根文件夹,但我希望它进入/ public / images。 I have a separate routes.js file to handle routes. 我有一个单独的route.js文件来处理路由。 This is how I've set up multer (in my routes.js file). 这就是我设置multer的方式(在我的route.js文件中)。

var multer = require('multer');
    var upload = multer({dest: '/public'});

The route for the POST request looks like this: POST请求的路由如下所示:

app.post('/upload', isLoggedIn, upload.single('file'), function (req, res) {
        var file = __dirname + req.file.filename;
        fs.rename(req.file.path, file, function (err) {
            if (err) {
                console.log(err);
                res.send(500);
            } else {
                res.json({
                    message: 'File uploaded successfully',
                    filename: req.file.filename
                });
            console.log(file);
            }
        });
    });

, and the form itself looks like this (it's an ejs file): ,表单本身看起来像这样(这是一个ejs文件):

<form method="post" action="/upload" enctype="multipart/form-data">
                    <label for="profilepicture">Profile picture</label>
                    <input type="file" name="file" accept="image/*">
                    <input type="submit" value="change profile picture">    
                    </form>

You are providing a wrong path in the dest , it's a relative path so it should be dest: 'public/' instead of dest: '/public' 您在dest中提供了错误的路径,这是相对路径,因此应为dest: 'public/'而不是dest: '/public'

Also, you are moving the file from the public folder by using fs.rename and the reason it is moved to outside the root folder is you are adding the root folder in the filename and not as a path : 另外,您正在使用fs.rename将文件从公用文件夹中fs.rename ,并将其移到根文件夹之外的原因是要在文件名中添加根文件夹,而不是将其作为路径:

var file = __dirname + req.file.filename;

should be : 应该 :

var file = __dirname + '/' + req.file.filename;

or even better : 甚至更好:

var file = path.join(__dirname, req.file.filename);

Overall, a working script with no need for the fs.rename : 总体而言,不需要fs.rename的工作脚本:

var multer = require('multer');
var upload = multer({dest: 'public/'});

app.post('/upload', isLoggedIn, upload.single('file'), function (req, res) {
  res.json({
    message: 'File uploaded successfully',
    filename: req.file.filename
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM