2017-03-08 70 views
0

我試圖將文件上傳到.net核心控制器方法,但是當控制器被觸發時,我的'文件'參數爲空。這是服務器端代碼...使用AJAX將文件上傳到dotnet核心

[HttpPost] 
    public async Task<IActionResult> UploadTimetable(long id, IFormFile file) 
    { 
     try 
     { 
      string fileContent; 

      using (var reader = new StreamReader(file.ThrowIfNull(nameof(file)).OpenReadStream())) 
      { 
       fileContent = await reader.ReadToEndAsync(); 
      } 
      await routeService.UpdateFromTimetableAsync(id, CsvGenerator.FromString(fileContent)); 
     } 
     catch (Exception ex) 
     { 
      return StatusCode(500, $"Unable to process Timetable ({ex.Message})"); 
     } 

     return Ok(new ApiServiceJsonResponse<Route>(HttpContextAccessor.HttpContext.Request, id, "routes")); 
    } 

路由觸發正常,但'文件'的值爲空。

我認爲這個問題可能與客戶端有關,因爲,在Chrome瀏覽器中,我在AJAX請求體內看不到任何東西。這是建立了這樣的...

/** 
* An AJAX request wrapper. 
* Usage of this enables testing AJAX calls. 
* 
* @export AjaxRequest 
* @class AjaxRequest 
* @extends {AjaxRequest} 
*/ 
export default class AjaxRequest { 

    /** 
    * Creates an instance of AjaxRequest. 
    * @param {any} { url, type, contentType, cache, processData, data, successCallback, errorCallback } 
    * 
    * @memberOf AjaxRequest 
    */ 
    constructor({ url, type, contentType, cache, processData, data, successCallback, errorCallback }) { 
     Guard.throwIf(url, "url"); 
     let emptyFunc =() => {}; 

     this.url = url; 
     this.type = type.toUpperCase() || "GET"; 
     this.contentType = contentType !== undefined ? contentType : "application/json; charset=utf-8"; 
     this.processData = processData !== undefined ? processData : true; 
     this.dataType = "json"; 
     this.cache = cache || false; 
     this.data = data ? JSON.stringify(data) : undefined; 
     this.successCallback = successCallback || emptyFunc; 
     this.errorCallback = errorCallback || emptyFunc; 
    } 

    /** 
    * Executes the AJAX request. 
    * 
    * @memberOf AjaxRequest 
    */ 
    execute() { 
     $.ajax({ 
      url: this.url, 
      type: this.type, 
      contentType: this.contentType, 
      processDAta: this.processData, 
      dataType: this.dataType, 
      cache: this.cache, 
      data: this.data, 
      success: this.successCallback, 
      error: this.errorCallback 
     }); 
    } 

    /** 
    * Gets a File Upload request. 
    * 
    * @static 
    * @param {string} url 
    * @param {array} files The files to upload 
    * @param {function} successCallback 
    * @param {function} errorCallback 
    * @returns 
    * 
    * @memberOf AjaxRequest 
    */ 
    static fileUpload(url, files, successCallback, errorCallback) { 
     let data = new FormData(); 

     for (let i = 0; i < files.length; i++) { 
      let file = files[i]; 
      data.append('file', file, file.name); 
     } 

     return new AjaxRequest({ 
      url: url, 
      type: 'POST', 
      data: data, 
      processData: false, // Don't process the files 
      contentType: false, // Set content type to false as jQuery will tell the server its a query string request 
      successCallback: successCallback, 
      errorCallback: errorCallback 
     }); 
    } 
} 

的「文件上傳」功能被稱爲與目標URL和在模式文件輸入HTML控件中的文件列表。此處的console.log表示文件列表按預期傳入,因此問題處於這些點之間的某處。

在Chrome中,我看不到表單數據元素的請求,我期望看到真的 - 我認爲我的數據對象結構有問題,但我似乎無法弄清楚。

從Chrome瀏覽器...

GENERAL 
Request URL:https://localhost:44333/Route/UploadTimetable/60018 
Request Method:POST 
Status Code:500 
Remote Address:[::1]:44333 

RESPONSE HEADERS 
content-type:text/plain; charset=utf-8 
date:Wed, 08 Mar 2017 18:02:41 GMT 
server:Kestrel 
status:500 
x-powered-by:ASP.NET 
x-sourcefiles:=?UTF-8?B?QzpcRGV2ZWxvcG1lbnRcQ2xpZW50c1xFc290ZXJpeFxNT0RMRSBPcGVyYXRpb25zXHNyY1xFc290ZXJpeC5Nb2RsZS5Qb3J0YWx3ZWJcUm91dGVcVXBsb2FkVGltZXRhYmxlXDYwMDE4?= 

REQUEST HEADERS 
:authority:localhost:44333 
:method:POST 
:path:/Route/UploadTimetable/60018 
:scheme:https 
accept:application/json, text/javascript, */*; q=0.01 
accept-encoding:gzip, deflate, br 
accept-language:en-GB,en-US;q=0.8,en;q=0.6 
cache-control:no-cache 
content-length:2 
content-type:text/plain;charset=UTF-8 
cookie: {removed} 
origin:https://localhost:44333 
pragma:no-cache 
referer:https://localhost:44333/Route/60018?Message=The%20route%20details%20have%20been%20updated. 
user-agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 
x-requested-with:XMLHttpRequest 

REQUEST PAYLOAD 
{} 

以上我所期望的展示形式的數據將不是嗎?

回答

0

錯誤在於這裏我AjaxRequest構造...

this.data = data ? JSON.stringify(data) : undefined; 

需求僅在JSON場景(因此它攪亂了身體),所以需要一個額外的參數響應有點像這個字符串化。 ..

this.stringify = stringify !== undefined ? stringify : true; 
this.data = data && stringify ? JSON.stringify(data) : data; 

我可以調用構造函數並使stringify爲false。

如果我不需要包裝我的AJAX調用,這將會更加明顯,但這是整個其他職位。