React setState不能分配fileList,而是分配第一个fileName的字符串。

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

首先,我正在做一个简单的社交媒体应用。我试图提交一个有文字、图片和视频的表单。我的前端是用React制作的,服务器是用nginx上的node.js运行的。我试图用下面的代码将输入的文件追加到FormData中。

handleSubmit = function (e) {
    e.preventDefault();
    const formData = new FormData();
    formData.append("textBody", this.state.textBody)
    for (let i = 0; i < this.state.imgInput.length; i++) {
        formData.append("imgInput", this.state.imgInput.files[i], "img"+i.toString())
    fetch("mywebsite.com/api/submitArticle", {
        body: formData,
        method: "POST",
        credentials: 'include',
    }).then((response) => console.log(response))
    return false;
}.bind(this)

handleChange = function (e) {
    e.preventDefault();
    if (e.target.name === 'imgInput') {
        this.setState({
            imgInput: e.target.files,
            showSpan: false
        })
    }
}.bind(this)

<form onSubmit={this.handleSubmit}>
        <textarea id='textBody' name='textBody' onFocus={removeSpan} onBlur={checkSpanOn} onChange={this.handleChange}/>
        <input type="file" id="imgInput" name="imgInput" accept="image/*" ref={this.imgRef}  multiple={true} onChange={this.handleChange}/>
        <input type="submit" id="submitButton" name="submitButton" formEncType="multipart/form-data" />
</form>

但是React在提交表单时给了我这个错误。

TypeError: Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'.

在 "formData.append("imgInput", this.state.imgInput.files[i], "img "+i.toString())"。

所以当我在handleChange中setState之前控制台记录e.target.files的内容时,我得到了正常的FileList,其中列出了所有的图片文件。但是当我在handleChange中setState之后控制台记录this.state.imgInput时,得到的是 C:/fakepathfilename的字符串。,而不是fileList。(最初state.imgInput是null。当我看到其他的例子和代码时,e.target.files是fileList,所以我很疑惑在其他地方我犯了错误。

我花了半天的时间在这个问题上,而且我还有5秒就要晕倒了,所以任何建议都将被感激:) 谢谢你的阅读。

html reactjs forms submit setstate
1个回答
0
投票

是的,这种情况发生,因为事件是走了,你需要存储事件.目标在变量+文件将在 imgInputimgInput.files 所以在这里,它是。

   handleSubmit = e => {
    e.preventDefault();
    const formData = new FormData();
    formData.append("textBody", this.state.textBody);
    for (let i = 0; i < this.state.imgInput.length; i++) {
      formData.append("imgInput", this.state.imgInput[i], "img" + i.toString());
       fetch("mywebsite.com/api/submitArticle", {
         body: formData,
         method: "POST",
         credentials: "include"
       }).then(response => console.log(response));
    }
  };

  handleChange = e => {
    e.preventDefault();
    const target = e.target;
    if (target.name === "imgInput") {
      this.setState(current => ({
        ...current,
        imgInput: target.files,
        showSpan: false
      }));
    }
  };
© www.soinside.com 2019 - 2024. All rights reserved.