简体   繁体   English

FormData Append 方法在 Angular 中不起作用

[英]FormData Append method doesn't work in Angular

I have an Angular app where I want to implement upload of images to the server.我有一个 Angular 应用程序,我想在其中实现将图像上传到服务器。 I'm stuck on the moment where I must append chosen file to the newly created FormData.我被困在必须将所选文件附加到新创建的 FormData 的那一刻。 Here is my TypeScript component relevant part:这是我的 TypeScript 组件相关部分:

imageData: File = null;
avatar = null;

fileProgress(fileInput: any) {
  this.imageData = <File>fileInput.target.files[0];
  this.avatar = new FormData();
  this.avatar.append('avatar', this.imageData);
  console.log(this.avatar, this.imageData)
}

This is what appears in console - FormData {} File {name: "background.jpg", lastModified: 1579183010623, lastModifiedDate: Thu Jan 16 2020 15:56:50 GMT+0200, webkitRelativePath: "", size: 8272, …}这是出现在控制台中的内容 - FormData {} File {name: "background.jpg", lastModified: 1579183010623, lastModifiedDate: Thu Jan 16 2020 15:56:50 GMT+0200, webkitRelativePath: "", size: 8272, …}

So basically I don't understand why I can't append already existing this.imageData with value to this.avatar , when I try to append it, it's value doesn't change and i still have empty array = FormData {} .所以基本上我不明白为什么我不能将已经存在的this.imageData与值附加到this.avatar ,当我尝试附加它时,它的值不会改变,我仍然有空数组 = FormData {} Any help would be appreciated.任何帮助,将不胜感激。

maybe you should investigate.也许你应该调查一下。

fileReader = new FileReader (); fileReader = new FileReader();

fileReader.onload = function(evt) { fileReader.onload = 函数(evt){

 ....

}) })

Appending a value to 'avatar' in FormData, adds a value to the 'avatar' key.将值附加到 FormData 中的 'avatar',将值添加到 'avatar' 键。 If you'd like to retrieve the values in a given key, you'd execute this.avatar.get('avatar')如果您想检索给定键中的值,您可以执行this.avatar.get('avatar')

It seems as though the file is retrieved and stored successfully in your example, is there anything that isn't working in particular?在您的示例中,似乎该文件已成功检索并存储,有什么特别不起作用的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM