expressjs multer不使用formData

问题描述 投票:1回答:1

我正在尝试使用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
});

反应客户

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'),但也没有运气。

我错过了什么?

express multipartform-data multer form-data
1个回答
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');
    })
  }
© www.soinside.com 2019 - 2024. All rights reserved.