所以我有一個與angular2的asp.net核心應用程序。現在我想上傳圖片,如果我將其上傳爲byte [],我就設法這樣做了。但後來我不能檢查文件是否真的在後端圖像,所以我試圖尋找另一種解決方案..我發現這個博客文件上傳:https://devblog.dymel.pl/2016/09/02/upload-file-image-angular2-aspnetcore/,但它不適合我...上傳圖像與angular2到asp.net核心
對於文件上傳我用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調用外觀像t他:
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。 當我添加圖像作爲字節[]它像一個魅力有什麼問題?爲什麼即使我傳遞的文件不爲null,我也總是爲空?我看到,當我改變從IFormFile類型FormFile我UserChange對象不是空了,但只是從文件對象參數是引發此錯誤
「userChange.File.ContentDisposition」其他東西扔類型的異常「System.NullReferenceException」
更新1
不知怎的,我管理使用這個答案發送文件asp.net控制器:File upload using Asp.Net Core Web API file is always null但這樣做,我不得不創建一個沒有參數的另一個動作, BU t如何發送文件在我的情況下仍然是未知的...