使用Express.js和Multer使用AJAX实现简单的多部分文件上传

2022-06-18 00:00:00 express jquery javascript ajax multer

我没有收到任何错误。文件夹uploads具有chmod 777

后端:

var multer  = require('multer');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads')
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
    }
});

var upload = multer({   storage: storage,
                        limits: { fileSize: '50mb' }}).single('photo');


router.post('/bild',function(req,res){
    console.log("REQ",req); //file is there in the body
    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
});

前端:

$("#formular").submit(function (e) {
        e.preventDefault();
        var form = $(this)[0];
        var formData = new FormData(form);
        console.log(formData)
        $.ajax({
            type: "POST",
            url: "/users/bild",
            data: formData,
            processData: false,
            "content-type": "application/x-www-form-urlencoded",
            success: function(r){
                console.log("result",r)
            },
            error: function (e) {
                console.log("some error", e);
            }
        });

    });

但未上载任何文件。我还尝试获取获取文件,并在发送之前将其附加到formData中-同样的效果。


解决方案

对于前端,contentType必须设置为False才能在jQuery.ajax中使用FormData对象,$(this)[0] === this

$("#formular").submit(function (e) {
    e.preventDefault();
    var formData = new FormData(this);
    console.log(formData)
    $.ajax({
        type: "POST",
        url: "/users/bild",
        data: formData,
        processData: false,
        contentType: false,
        success: function(r){
            console.log("result",r)
        },
        error: function (e) {
            console.log("some error", e);
        }
    });

});

相关文章