首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何修复FormData.entries()不起作用

如何修复FormData.entries()不起作用
EN

Stack Overflow用户
提问于 2019-06-03 07:01:07
回答 1查看 1.7K关注 0票数 0

我有一个要上传到远程服务器的<input type="file">。我看过一个视频,这是通过将选定的文件对象附加到FormData对象并使用http发送来实现的。

问题是我的FormData对象是空的。我在网上看到,要检查FormData,需要遍历FormData.entries(),但我得到了一个错误entries is not a known property of "FormData"。我看到一个在线修复,涉及添加以下内容:

代码语言:javascript
复制
declare global {
    interface FormData {
      entries(): Iterator<[USVString, USVString | Blob]>;
    }
  }

添加到我的polyfills.ts文件中,然后使用type USVString = string;在@types/usvstring.d.ts .d.ts中声明USVString,并将types = ["../@types/usvstring"]添加到tsconfig.app.json中。我已经做了所有这些,但仍然得到一个编译错误:

代码语言:javascript
复制
ERROR in src/app/selection/selection.component.ts(38,25): error TS2495: Type 'Iterator<[string, string | Blob]>' is not an array type or a string type.

有谁知道怎么解决这个问题吗?

我的源码在这里:

代码语言:javascript
复制
<h1>UPLOAD PHOTO</h1>
<input type="file" (change)="onSelectFile($event)">
<button (click)="uploadFiles()">Upload</button>
代码语言:javascript
复制
  onSelectFile(event) {
     this.selectedFile = <File>event.target.files[0];
  }

  uploadFiles() {
    let fd = new FormData();

    fd.append('image',this.selectedFile,this.selectedFile.name);

    for (const entry of fd.entries()) {  // <-- ENTRIES() NOT RECOGNIZED
      console.log(entry);
    }

    this.http.post("localhost:3000/test-photo",fd)
      .subscribe((res) => {
        console.log(res);
      });
  }
EN

回答 1

Stack Overflow用户

发布于 2019-06-03 09:29:31

正如我在评论中提到的,我将分享我在FormData中迭代的解决方法。

根据FormData.entries()documentation,它似乎确实不被旧版本的火狐支持,因为它只被44版本或更高版本支持。同样,Internet Explorer (IE)以及Safari 11之前的任何版本都不支持它。

因此,我所做的是创建一个字典,然后手动将其映射到您的FormData。因此,如果出于任何目的(例如调试或其他)需要迭代它,则需要迭代字典而不是FormData本身。

代码语言:javascript
复制
const formDataDictionary = {
  'image': this.selectedFile,
  'image2': this.selectedFile2
};

const fd = new FormData();
for (const key in formDataDictionary) {
  fd.append(key, formDataDictionary[key]);
}

或者,您可以使用ES6的扩展语法来遍历FormData,这应该可以很好地工作,因为Angular将为您做转译工作。

代码语言:javascript
复制
const fd = new FormData();
fd.append('image',this.selectedFile,this.selectedFile.name);
console.log(...fd);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56419580

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档