我有一个要上传到远程服务器的<input type="file">
。我看过一个视频,这是通过将选定的文件对象附加到FormData
对象并使用http
发送来实现的。
问题是我的FormData
对象是空的。我在网上看到,要检查FormData
,需要遍历FormData.entries()
,但我得到了一个错误entries is not a known property of "FormData"
。我看到一个在线修复,涉及添加以下内容:
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
中。我已经做了所有这些,但仍然得到一个编译错误:
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.
有谁知道怎么解决这个问题吗?
我的源码在这里:
<h1>UPLOAD PHOTO</h1>
<input type="file" (change)="onSelectFile($event)">
<button (click)="uploadFiles()">Upload</button>
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);
});
}
发布于 2019-06-03 09:29:31
正如我在评论中提到的,我将分享我在FormData中迭代的解决方法。
根据FormData.entries()
的documentation,它似乎确实不被旧版本的火狐支持,因为它只被44版本或更高版本支持。同样,Internet Explorer (IE)以及Safari 11之前的任何版本都不支持它。
因此,我所做的是创建一个字典,然后手动将其映射到您的FormData。因此,如果出于任何目的(例如调试或其他)需要迭代它,则需要迭代字典而不是FormData本身。
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将为您做转译工作。
const fd = new FormData();
fd.append('image',this.selectedFile,this.selectedFile.name);
console.log(...fd);
https://stackoverflow.com/questions/56419580
复制相似问题