所以我有 Angular2 的 ASP.NET Core 应用程序。现在我想上传图像,如果我将其上传为 byte[],我就成功了。但后来我无法检查文件是否真的是后端的图像,所以我尝试寻找其他解决方案。我发现了这个关于文件上传的博客:https://devblog.dymel.pl/2016/09/02/upload-file-image-angular2-aspnetcore/ https://devblog.dymel.pl/2016/09/02/upload-file-image-angular2-aspnetcore/但这对我不起作用......
对于文件上传,我使用 angular2 库Angular2 图像上传,所以我的图像上传的 html 部分如下所示:
<image-upload [max]="1" [buttonCaption]="'Browse'" [preview]="false" (change)="onFileChange($event)"></image-upload>
<button (click)="onSaveChanges()" class="btn btn-primary float-left" type="submit">Save</button>
然后我的 angular2 部分看起来像这样:
onFileChange(event: any) {
this.file = event.target.files[0];
if (event.target.files && this.file) {
var reader = new FileReader();
reader.onload = (event: any) => {
this.profilePicture = event.target.result;
}
reader.readAsDataURL(this.file);
}
}
onSaveChanges() {
this.isSaving = true;
this.country = this.state.user.country;
this.userService.userChange(this.firstName, this.lastName, this.country, this.file, this.currentPassword, this.newPassword).subscribe(success => {
this.state.user.profilePicture = this.profilePicture;
this.state.user.firstName = this.firstName;
this.state.user.lastName = this.lastName;
this.isSaving = false;
this.passwordError = false;
this.isSuccessful = true;
this.currentPassword = '';
this.newPassword = '';
this.newPasswordRepeat = '';
}, error => {
this.isSaving = false;
this.passwordError = true;
this.passwordErrorMessage = error._body;
});
}
我的 angular2 api 调用如下所示:
userChange(firstName: string, lastName: string, country: string, file: File, oldPassword: string, newPassword: string) {
let input = new FormData();
input.append("File", file);
var url = this.baseUrl + "updateUser";
return this.http.post(url, { FirstName: firstName, LastName: lastName, Country: country, File: input, OldPassword: oldPassword, NewPassword: newPassword });
}
我的 asp.net 核心控制器(请注意,我没有显示控制器的主体,因为它不相关):
[HttpPost]
public async Task<IActionResult> UpdateUser([FromBody]UserChange userChange)
{
}
用户更改类:
public class UserChange
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Country { get; set; }
public IFormFile File { get; set; }
public string OldPassword { get; set; }
public string NewPassword { get; set; }
}
问题是,当我提交图像时,我总是将 UserChange 对象设置为 null。当我将图像添加为 byte[] 时,它就像一个魅力问题是什么??为什么即使我传递的文件不为空,我也总是为空?我看到的另一件事是,当我将类型从 IFormFile 更改为 FormFile 时,我的 UserChange 对象不再为 null,但只有对象中的 File 参数抛出此错误
“userChange.File.ContentDisposition”引发了“System.NullReferenceException”类型的异常
UPDATE 1
不知怎的,我设法使用这个答案将文件发送到 asp.net 控制器:使用Asp.Net Core Web API上传文件文件始终为空 https://stackoverflow.com/questions/44097604/file-upload-using-asp-net-core-web-api-file-is-always-null但要做到这一点,我必须创建另一个没有参数的操作,但在我的情况下如何发送文件仍然未知......