2017-09-24 137 views
1

我對react.js和ASP.Net core 2.0都很陌生。現在用ASP.Net core 2.0編寫一個項目作爲後端API,react.js作爲應用程序接口(前端)。我想知道如何上傳文件。我試過如下,但在後端側參數值(IFromFile文件)始終爲空。而且似乎該文件沒有正確發佈。這裏是我的代碼:使用ASP.Net Core 2.0 Web API和React.js進行文件上傳

的.Net核心(API)

[HttpPost] 
     [Route("upload")] 
     public async Task Upload(IFormFile file) 
     { 
      if (file == null) throw new Exception("File is null"); 
      if (file.Length == 0) throw new Exception("File is empty"); 

      using (Stream stream = file.OpenReadStream()) 
      { 
       using (var binaryReader = new BinaryReader(stream)) 
       { 
        var fileContent = binaryReader.ReadBytes((int)file.Length); 
        // await _uploadService.AddFile(fileContent, file.FileName, file.ContentType); 
       } 
      } 
     } 

React.js

handleClick(event){ 
     event.preventDefault(); 
     // console.log("handleClick",event); 
     var self = this; 
     var apiBaseUrl = axios.defaults.baseURL + "user/upload"; 
     if(this.state.filesToBeSent.length>0){ 
      var filesArray = this.state.filesToBeSent; 
      const reader = new FileReader(); 
      for(var i in filesArray){ 
       //console.log("files",filesArray[i][0]); 
       var file = filesArray[i][0]; 
       axios.post(apiBaseUrl, {data: file}); 
      } 
      alert("File upload completed"); 
     } 
     else{ 
      alert("Please select files first"); 
     } 
    } 

請告知我怎樣才能解決這個問題。

回答

1

我已經做的工作​​如下:

在使用Microsoft.AspNetCore.Http的.Net核心2.0網頁API

;

我創建了一個模型類

namespace Marter_MRM.Models 
{ 
    public class FileUploadViewModel 
    { 
     public IFormFile File { get; set; } 
     public string source { get; set; } 
     public long Size { get; set; } 
     public int Width { get; set; } 
     public int Height { get; set; } 
     public string Extension { get; set; } 
    } 
} 

然後我創建了一個控制器類和編寫的函數如下。

[HttpPost] 
[Route("upload")] 
public async Task<IActionResult> Upload(FileUploadViewModel model) { 
     var file = model.File; 

     if (file.Length > 0) { 
      string path = Path.Combine(_env.WebRootPath, "uploadFiles"); 
      using (var fs = new FileStream(Path.Combine(path, file.FileName), FileMode.Create)) 
      { 
       await file.CopyToAsync(fs); 
      } 

      model.source = $"/uploadFiles{file.FileName}"; 
      model.Extension = Path.GetExtension(file.FileName).Substring(1); 
     } 
    return BadRequest(); 
} 

和寫入API調用函數如下反應:

handleUploadClick(event){ 
    event.preventDefault(); 
    var self = this; 
    var apiBaseUrl = axios.defaults.baseURL + "user/upload"; 
    if(this.state.filesToBeSent.length>0){ 
     var filesArray = this.state.filesToBeSent; 
     let f = new FormData(); 
     for(var i in filesArray){ 
     //console.log("files",filesArray[i][0]); 
      f = new FormData(); 
      f.append("File",filesArray[i][0]) 
      axios.post(apiBaseUrl, f, { 
        headers: {'Content-Type': 'multipart/form-data'} 
      }); 
     } 
     alert("File upload completed"); 
    } 
    else{ 
     alert("Please select files first"); 
    } 
} 

它可以完美運行。謝謝!