代码之家  ›  专栏  ›  技术社区  ›  assembler

尝试上载传递名称的txt文件时出错

  •  0
  • assembler  · 技术社区  · 5 年前

    我有一个加载txt文件的组件,然后我试图上传该txt文件,并在请求中传递名称,我得到的文件如下:

    const fetch = ({ target }) => {
        const reader = new FileReader();
        const file = target.files[0];
        if (file) {
          reader.readAsText(file);
          reader.onloadend = e => {
            setFileContents(e.target.result);
          };
        }
      };
    

    const URL = 'myURL';
                    const formData = new FormData();
                    formData.append('file', fileContents);
                    fetch(URL, {
                      method: 'PATCH',
                      headers: // ... my headers,
                      body: formData
                    })
                      .then(response => response.json())
                      .then(data => {
                        // success
                      })
                      .catch(() => {
                        // error
                      });
    

    这种方法有效,但根据 this formData.append(name, value, filename); 是允许的,但如果我这样做:

     formData.append('file', fileContents, 'myFile');
    

    浏览器的控制台会大叫:

    未捕获的TypeError:未能对“FormData”执行“append”:参数2不是“Blob”类型

    我怎样才能克服这一点?我错过了什么?

    1 回复  |  直到 5 年前
        1
  •  1
  •   assembler    5 年前

    我在谷歌上做了更多的工作,我发布了这个解决方案,希望任何人都能使用它:

    自从 fileContents 是将其转换为文件所需的字符串,我执行了以下操作:

    const myBlob = new Blob([fileContents], { type: 'text/plain' });
    const myFile = new File([myBlob], { type: 'text/plain' });
    

    formData.append('file', myFile, 'myFile');
    

    工作起来很有魅力。所以,如果有更好的方法,请告诉我。