2016-09-27 64 views
1

我想從FormData xhr請求保存傳入的文件,但我甚至不能解析傳入的請求。這是如何我要發送的文件:如何使用Express 4和Multer保存文件?

... 
    let xhr = new XMLHttpRequest(), 
    formData = new FormData(); 

    for(let i = 0; i < this.files.length; i++) { 
     formData.append(this.files[i], this.files[i].name); 
    } 
    xhr.open('POST', URL, true); 
    xhr.send(formData); 
... 

這是如何我試圖抓住它:

var express = require('express'); 
var router = express.Router(); 
var multer = require('multer'); 
var uploads = multer({dest: './uploads/'}); 

router.post('/upload', uploads.any(), function (req, res) { 
    console.log(req.files); // [] 
    console.log(req.file); // undefined 
    console.log(req.body); //{ '[object File]': '20160715_104330.jpg' } 
}); 

的圖像來在服務器上,但沒有寫入該目錄上傳。

如何將圖像保存在目錄上傳中?

回答

1

我發現了錯誤。以下是更正的代碼行:

​​

我只需要把第一個參數是一個字符串表示字段名。

查看在後端的結果:

var express = require('express'); 
var router = express.Router(); 
var multer = require('multer'); 
var uploads = multer({dest: './uploads/'}); 

router.post('/upload', uploads.any(), function (req, res) { 
    console.log(req.files); 
    /* [ { fieldname: 'Choose your Fieldname', 
      originalname: '20160715_104330.jpg', 
      encoding: '7bit', 
      mimetype: 'image/jpeg', 
      destination: './uploads/', 
      filename: '72b7a52101537ab1006f4feb0fa752be', 
      path: 'uploads\\72b7a52101537ab1006f4feb0fa752be', 
      size: 233509 } ] 
    */ 
    console.log(req.file); // undefined 
    console.log(req.body); //{} 
}); 

下面是在前端一個較小的代碼:

... 
    upload(){ 
     let xhr = new XMLHttpRequest(), 
     formData = new FormData(); 
     formData.append('Choose your Fieldname', this.files[0], this.files[0].name); 
     xhr.open('POST', URL, true); 
     xhr.send(formData); 
    } 
... 
相關問題