使用multer上传文件并传递额外参数

13

我正在使用jQuery表单插件multer来上传文件到我的服务器。这个功能很好用,但是我想传递一个额外的参数,以确定文件将被保存在哪里。

我有以下代码,我想扩展功能以满足要求:

HTML

<form id="uploadForm"
      enctype="multipart/form-data"
      action="/files"
      method="post">
    <input type="file" id="userFile" name="userFile"/>
    <input type="text" hidden id="savePath" name="savePath" value="path"/>
</form>

客户端JS

uploadForm.submit(function() {
    $(this).ajaxSubmit({

        error: function(xhr) {
            console.log('Error: ' + xhr.status);
        },

        success: function(response) {
            console.log('Success: ' + response);
        }
    });

    return false;
});

Node.js 路由

app.post(APIpath + "file",function(req,res){
    var storage = multer.diskStorage({
        destination: absoluteServePath+ "/" + config.filePath,
        filename: function (req, file, cb) {
            cb(null, file.originalname);
        }
    });
    var upload = multer({ storage : storage}).any();

    upload(req,res,function(err) {
        if(err) {
            console.log(err);
            return res.end("Error uploading file.");
        }
        res.end("File has been uploaded");
    });
});

注意: 我知道我现在没有检查MIME类型或对用户文件进行清理,但对我来说主要是次要的。


你可以从 req.body 中获取 savePath - stdob--
嗯,我只能得到一个 userFile 对象,无论我尝试了多少次,savePath 从未出现在 req.body 中。 - Clemens Himmer
1个回答

33

问题在于multer首先保存文件,然后才将表单的其余部分(如隐藏字段)写入req

尝试此操作:

app.post(APIpath + "file",function(req,res){
    var storage = multer.diskStorage({
        destination: tmpUploadsPath
    });
    var upload = multer({ storage : storage}).any();

    upload(req,res,function(err) {
        if(err) {
            console.log(err);
            return res.end("Error uploading file.");
        } else {
           console.log(req.body);
           req.files.forEach( function(f) {
             console.log(f);
             // and move file to final destination...
           });
           res.end("File has been uploaded");
        }
    });
});

你好。请帮忙添加一个移动到最终目的地的示例。对于我的情况,我想要移动到@stdob的云位置。 - O'Dane Brissett
1
我无法访问在文件后附加的主体值。因此,我将文件附加在最后。 - Ataberk
非常感谢您!帮了我很多!我必须使用req.file来获取我所需的内容,因此如果上述方法对您不起作用,只需记录body以查看您需要的内容是否在其中。 - DORRITO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接