【问题标题】:I can't upload image to backend with fetch in REACT我无法通过 REACT 中的 fetch 将图像上传到后端
【发布时间】:2019-11-19 12:25:07
【问题描述】:

我马上进入正题。

我在 REACT 中有这个简单的表格。它有 2 个输入字段和 1 个图像上传字段。我需要将数据发送到使用 Spring 制作的后端 API。

我正在尝试这个

const formID = document.getElementById('formGroup');
const formData = new FormData(formID);

fetch('api/5/add-image', {
  method: 'POST',
  body: JSON.stringify(formData),
  headers: {
    Authorization: 'Bearer ' + token,
    Accept: 'application/json',
    'Content-Type': 'multipart/form-data'
  }
}).then(res => {
   this.setState({ isSubmitting: false });
   console.log(res.text());
})

但我经常在控制台中收到相同的错误消息

Required request part 'file' is not present

任何想法可能导致问题?身份验证令牌有效,我认为标头还可以。

感谢您的宝贵时间:)

【问题讨论】:

    标签: javascript reactjs spring


    【解决方案1】:

    在使用 FormData 和 fetch 时,您不应该对表单值进行字符串化,并且不要指定 Content-Type 标头

    应该这样做

    const formID = document.getElementById('formGroup');
    const formData = new FormData(formID);
    fetch('api/5/add-image', {
      method: 'POST',
      body: formData,
      headers: {
        Authorization: 'Bearer ' + token,
        Accept: 'application/json',
      }
    }).then(res => {
       this.setState({ isSubmitting: false });
       console.log(res.text());
    })
    

    【讨论】:

    • 感谢您的宝贵时间,但Current request is not a multipart form request 是我删除Content-Type 后收到的消息编辑 抱歉。我的错。我仍然收到关于文件不存在的相同错误
    • 您是否仔细检查了文件输入的name 属性是否与您的服务器期望的相同?
    • 非常感谢。你不知道我尝试了多久。这就是问题所在。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多