expressjs multer不使用formData

时间:2018-03-03 01:48:59

标签: express multipartform-data multer form-data

我正在尝试使用react.js客户端上传图像并表达后端。我似乎无法使用FormData对象。

示例代码:

服务器

var express = require('express');
var app = express();
var multer  = require('multer');
var upload = multer({ dest: 'uploads/' });

app.put('/upload', upload.single('file'), function(req, res) {
  console.log(req.file);  // This is undefined
});

React Client

class Upload extends Component {
  onDrop(file) {
    let formData = new FormData();
    formData.append('file', file);

    fetch('/upload', {
      method: 'PUT',
      body: formData
    })
  }
})

网络请求为CURL

curl 'http://localhost:3000/upload' -X PUT -H 'Pragma: no-cache' -H 'Origin: http://localhost:3000' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-US,en;q=0.9,en-CA;q=0.8' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36' -H 'Content-Type: multipart/form-data; boundary=----WebKitFormBoundary9G2UBtVoQGWfYcDA' -H 'Accept: */*' -H 'Cache-Control: no-cache' -H 'Referer: http://localhost:3000/upload' -H 'Connection: keep-alive' --data-binary $'------WebKitFormBoundary9G2UBtVoQGWfYcDA\r\nContent-Disposition: form-data; name="file"\r\n\r\n[object File]\r\n------WebKitFormBoundary9G2UBtVoQGWfYcDA--\r\n' --compressed

我也试过了 我的react.js客户端代码中的formdata.append('name', 'file'),但也没有运气。

我错过了什么?

1 个答案:

答案 0 :(得分:0)

这是我用于相同目的的代码,使用react和nodejs上传照片。希望这会有所帮助:

服务器:

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'routes/')
  },
  filename: function (req, file, cb) {
    cb(null, 'bat' + path.extname(file.originalname))
  }
});
const upload = multer({ storage: storage });

route.post('/', upload.single('image'), (req, res) => {
    console.log(req.file);
});

App.js - 上传并提交:

  uploadImage(e){
    e.preventDefault();
    let reader = new FileReader();
    let file = e.target.files[0];
    this.setState({obj: file})
    reader.onloadend = () => {
      this.setState({
        file: file,
        url: reader.result 
      })
    }
    if(file){
      reader.readAsDataURL(file);
    }
  }

  submitImage(e){
    e.preventDefault();
    var data = new FormData();
    data.append('image', this.state.file);
    axios.post(url, data, {headers: { 'Content-Type': 'multipart/form-data' } })
    .then(res => {
      console.log(res);
    }).catch(err => {
      console.log('err');
    })
  }