无法使用multer上传文件

时间:2017-10-13 07:24:55

标签: node.js reactjs multer

我已经看到了许多答案,并尝试了几乎所有的答案,但似乎没有一个对我有用。我可以将表单数据打印为ascii字符,但我没有按预期看到存储在public / uploads文件夹中的文件。我可以使用API​​在react app上读取和呈现存储的文件,但无法上传它。我没有错误,一切正常但文件夹中没有上传文件。我尝试使用multer上传文件,以下是代码段:

路由/ uploads.js

var storage = multer.diskStorage({
    dest : function (req, file, cb) {
        cb(null, path.join(__dirname, 'public/uploads/'))
    }
});

var upload = multer({storage:storage}) ;

router.post('/upload', upload.single('mypic'), function (req, res, next) {
    console.log("inside upload files");
    console.log(req.body); //prints non-readable characters as I am uploading image as expected               
    console.log(req.file); //says undefined
    return res.status(204).end();
});

API.js(反面):

export const uploadFile = (payload) =>   //payload is actually formdata
  fetch(`${api}/files/upload`,
      {
        method: 'POST',
        //headers: { 'Content-Type': 'application/json' },                        
        headers: {              
          'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
        },            
        body: payload
    }
)
.then(res => {
    console.log(res);
    return res.status;
})
.catch(error => {
        console.log(error);
        return error;
});

2 个答案:

答案 0 :(得分:0)

尝试删除:

'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'

答案 1 :(得分:0)

尝试以下IT包含多个部分:

var storage = multer.diskStorage({
        destination: function (req, file, cb) {

            const extension = file.mimetype.split('/')[1];
           //you can change destination runtime
            if(file.fieldname == "covers[]")
            {
                cb(null, __dirname, '../public/uploads/cover');
                return;
            }
            else
            {
                cb(null, '../public/uploads/image');
                return;
            }

        },
        filename: function (req, file, cb) {
            //you can also change name

            cb(null, filename)
        }
    });

    var upload = multer({
        storage: storage,
    });