使用express.js上传简单的multipart文件,使用ajax上传multer

时间:2017-07-16 17:37:12

标签: javascript jquery ajax express multer

我没有收到任何错误。文件夹uploadschmod 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 - 效果相同。

1 个答案:

答案 0 :(得分:3)

对于前端,必须将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);
        }
    });

});