2017-06-27 112 views
3

所以我有一個與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如何發送文件在我的情況下仍然是未知的...

回答

0

我找到你的文章時,尋找做類似的事情,也開始使用angular2圖像上傳庫,但決定嘗試簡單的方法先。出於我的目的,我只需要byte []圖像文件(將嘗試爲圖像標題和標題添加表單字段),並發現Michael Dymel在他的博客文章中建議的一些非常有用的工具。儘管你無法讓自己的工作方式得到實現,但它對我有很大的幫助。

我從哪裏冒出來的是配置正確的路由,一段時間它看起來像我的文件正在角度服務中正確拾取,但它到達'上載'控制器時爲空。一旦我檢查到上傳服務的路徑和控制器的[Route(「/ api/upload」)]屬性中定義的路徑是相同的,這一切都落在原地,我能夠成功上傳。稍有不同的問題你有什麼,但是這個工作對我來說:

我的上傳組件方法:

addFile(): void { 
    let fi = this.fileInput.nativeElement; 
    if (fi.files && fi.files[0]) { 
     let fileToUpload = fi.files[0]; 

     if (fileToUpload) { 
      this.uploadService.upload(fileToUpload) 
      .subscribe(res => { 
       console.log(res); 
      }); 
     } 
     else 
      console.log("FileToUpload was null or undefined."); 
    } 
} 

調用上傳服務:

upload(fileToUpload: any) { 
     let input = new FormData(); 
     input.append("fileForController", fileToUpload); 
     return this.http.post("/api/upload", input); 
    } 

哪些職位進入「上傳'我的ImagesController的ActionResult,看起來像這樣(我將圖像保存到數據庫中,所以'path'變量實際上是多餘的)。在「圖像」對象就是URL,標題,ImageFileContent和標題字段一個簡​​單的模型:

[HttpPost] 
[Route("/api/upload")] 
public async Task<IActionResult> Upload(IFormFile fileForController) 
{ 
    if (!ModelState.IsValid) 
    { 
     return BadRequest(ModelState); 
    } 

    if (fileForController == null) throw new Exception("File is null"); 
    if (fileForController.Length == 0) throw new Exception("File is empty"); 

    var theImage = new Image(); 
    var path = Path.Combine("~\\ClientApp\\app\\assets\\images\\", fileForController.FileName); 

    theImage.Url = path + fileForController.FileName; 
    theImage.Title = fileForController.Name + "_" + fileForController.FileName; 
    theImage.Caption = fileForController.Name + " and then a Surprice Caption"; 

    using (Stream stream = fileForController.OpenReadStream()) 
    { 
     using (var reader = new BinaryReader(stream)) 
     { 
      var fileContent = reader.ReadBytes((int)fileForController.Length); 

      theImage.ImageFileContent = fileContent; 
      _context.Images.Add(theImage); 

      try 
      { 
       await _context.SaveChangesAsync(); 
      } 
      catch (Exception ex) 
      { 
       throw new Exception(ex.Message); 
      } 
     } 
    } 
    return Ok(theImage); 
} 

而我的HTML模板領域是幾乎完全按照邁克爾Dymel的帖子:

<form action="gallery" name="fileUploadForm" method="post" enctype="multipart/form-data"> 
    <div class="col-md-6"> 
     <input #fileInput type="file" title="Choose Image to upload" /> 
     <button (click)="addFile()" class="btn btn-success">Add</button> 
    </div> 
</form>