【问题标题】:Uploading an image with multer / react-dropzone使用 multer / react-dropzone 上传图片
【发布时间】:2018-09-17 17:02:58
【问题描述】:

我似乎无法使用 express、multer 和 react-dropzone 将图像上传到我的上传文件夹。我的代码如下:

<Dropzone
    style={{position: "relative"}}
    accept="image/*, video/*"
    onDrop={this.onDrop.bind(this)}
    onDragEnter={this.onDragEnter.bind(this)}
    onDragLeave={this.onDragLeave.bind(this)}
    name='avatar'
  >
    { dropzoneActive && <div style={overlayStyle}>Drop files...</div> }
    <div>

      <h2>Dropped files</h2>
      {

          files.map(f => <div><li>{f.name} - {f.size} bytes</li> 
          <img style={{height:'100px'}}src={f.preview}/></div>)
      }
    </div>
  </Dropzone>

使用 dropzone 示例的基本文件上传。那么我的提交函数是:

createBlog(){

var file = this.state.files[0];
var file_name = file.name;
//api/blog
fetch('http://localhost:8080/saveBlog', {
method: 'POST',
headers: {
  "Accept": 'application/json',
  'Content-Type': 'application/json',
  //"Content-Type": "application/x-www-form-urlencoded"
},
body: JSON.stringify({
  file: file,
  file_name: file_name
})
  }).then((response) =>  {
  ...
  }))
  }, function(error) {
   console.log('error: ',error.message)
  })
}

注意 file 返回图像具有的所有属性,例如lastModifiedDate、名称、预览、大小、类型、webkitRelativePath。

但是,当我将数据传递给服务器时,我得到的响应是:

{ file:
 { preview: 'blob:http://localhost:3000/954e0002-3045-44c4-bcd8-70dc26d0d416' 
},
file_name: 'image.jpg' } 'Body'
undefined 'files'

我的涉及图像的服务器代码在哪里:

var multer = require('multer');
var upload = multer({ dest: './uploads/' });
...
...
router.post('/saveBlog', upload.single('avatar'), function(req, res, next) {
    console.log(req.body, 'Body');
    console.log(req.file, 'files');
    res.end();
});

我希望有人可以帮助告诉我为什么我的图片没有进入我的上传文件夹,因为我花了很长时间试图弄清楚这个基本示例。

【问题讨论】:

    标签: reactjs express multer react-dropzone


    【解决方案1】:

    您的问题是您正在尝试将JSON.stringify() 用于您的请求负载,而 Multer 期望并且仅适用于 formData。您还需要删除您拥有的标题或使用'content-type': 'multipart/form-data'

    你有:

    body: JSON.stringify({
      file: file,
      file_name: file_name
    }) 
    

    你需要使用 formData() 代替:

    createBlog(){
    
        const file = this.state.files[0];
        const file_name = file.name;
        let data = new FormData();
        data.append('file', file);
        data.append('file_name', file_name);
    
        fetch('http://localhost:8080/saveBlog', {
           method: 'POST',
           body: data
             }).then((response) =>  {
                ...
             }))
             }, function(error) {
              console.log('error: ',error.message)
        })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-22
      • 2021-05-30
      • 2018-12-16
      • 2021-10-17
      • 1970-01-01
      • 2016-06-14
      • 2018-10-23
      • 1970-01-01
      相关资源
      最近更新 更多