【发布时间】:2017-11-30 10:00:23
【问题描述】:
所以我有 angular2 的 asp.net 核心应用程序。现在我想上传图片,如果我将它上传为 byte[],我设法做到了。但后来我无法检查文件是否是后端中的真实图像,所以我试图寻找其他解决方案。我发现这个关于文件上传的博客:https://devblog.dymel.pl/2016/09/02/upload-file-image-angular2-aspnetcore/ 但它对我不起作用......
对于文件上传,我使用 angular2 库 angular2-image-upload,所以我的图片上传的 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)
{
}
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 对象不再为空,但只有来自对象的 File 参数抛出此错误
“userChange.File.ContentDisposition”引发了“System.NullReferenceException”类型的异常
更新 1
不知何故,我设法使用以下答案将文件发送到 asp.net 控制器:File upload using Asp.Net Core Web API file is always null 但为此我必须创建另一个没有参数的操作,但在我的情况下如何发送文件仍然未知......
【问题讨论】:
标签: c# asp.net image angular file-upload