【问题标题】:Make a POST form-data with React to upload an image使用 React 制作 POST 表单数据以上传图像
【发布时间】:2021-08-14 08:58:16
【问题描述】:

我正在尝试通过我的 API 将我的 ReactJS 服务中的图像上传到我的 NestJS API 服务,但它还没有工作。这是 React 代码:

首先是表格:

<div>
 <input type="file" name="urlpromo" value={urlpromo} onChange={this.changeHandler} />
</div>
<button type="submit">Submit</button>

和功能:

changeHandler = (e) => {
    this.setState({[e.target.name]: e.target.value})
}

submitBaner = (e) => {
        var bodyFormData = new FormData();

        bodyFormData.append('file', this.state.urlpromo);
        
        let config = {
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'multipart/form-data',
              }
        }
        e.preventDefault()
        console.log(bodyFormData)
        axios.post('http://localhost:3000/images/upload', bodyFormData,config)
    }

问题是,在我发送图像之前,仅使用 JSON 正文,它工作正常,但现在使用表单数据,我无法让它工作。这就是我可以使用 Postman 上传图片的方式:

当我尝试让它工作时,功能控制台日志会打印:

FormData {}__proto__: FormData

我做错了什么,我应该如何处理这个表单数据?

【问题讨论】:

  • 这是邮递员的工作吗?
  • 不要尝试记录FormData 实例,它不可序列化

标签: reactjs axios postman nestjs


【解决方案1】:

根据the docs&lt;input type="file"&gt; 由于其只读值而不受控制

一种选择是使用ref 来跟踪&lt;input&gt; 元素和files 属性来访问File

// in your constructor
this.urlPromoRef = React.createRef()
<div>
 <input type="file" ref={this.urlPromoRef} />
</div>
<button type="submit">Submit</button>

在您的提交处理程序中

e.preventDefault()
const bodyFormData = new FormData();
bodyFormData.append('file', this.urlPromoRef.files[0]);

// no need for extra headers
axios.post('http://localhost:3000/images/upload', bodyFormData)

另一种选择是将&lt;form&gt; 本身传递给FormData 构造函数。

<form onSubmit={this.submitBaner}>
  <div>
    <input type="file" name="urlpromo" /> <!-- must have a name -->
  </div>
  <button type="submit">Submit</button>
</form>
submitBaner = (e) => {
  e.preventDefault()

  const bodyFormData = new FormData(e.target); // pass in the form

  axios.post('http://localhost:3000/images/upload', bodyFormData)
}

最后,您可以使用类似于原始代码的代码,但需要对&lt;input type="file"&gt; 进行特殊检查。例如

changeHandler = (e) => {
  const el = e.target
  this.setState({
    [el.name]: el.type === "file" ? el.files[0] : el.value
  })
}

【讨论】:

  • 谢谢,我用 ChangeHandler 修复了它
猜你喜欢
  • 2015-05-20
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-13
  • 2018-10-16
相关资源
最近更新 更多