1

我正在尝试选择图像并将其发送到服务器,但是当我发送它时,它说字段文件为空。如果我不使用FormData. 屏幕截图

我的代码:

import axios from "axios";
import React, { Component } from "react";
export default class UploadImage extends Component {
    handleChange= async (event)=>{
        const img = event.target.files[0]
        console.log(img)
        const fd = new FormData();
        fd.append('image',img, img.name)
        console.log(fd)
        const res = await axios.post(`http://localhost:5000/upload`,{file:img})
        // console.log(res)
    }
  render() {
    return (
      <div>
        <div class="custom-file mb-3">
            <input id="img" type="file" name="file"  class="custom-file-input" onChange={this.handleChange}/>
            <label for="file" class="custom-file-label">Choose File</label>
          </div>
       </div>
    );
  }
}

4

1 回答 1

0

问题出在两个部分:

1)fd.append('image',img, img.name)第一个字段必须等于后端的字段,upload.single('file')因为"image"并且"file"不匹配,所以它会产生问题。

2)在 axios 请求await axios.post("http://localhost:5000/upload",{file:img}) 中,第二个字段必须只是formdate变量,所以它应该是,await axios.post("http://localhost:5000/upload",fd)

于 2019-07-25T14:06:14.243 回答