2017-03-08 39 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调用,这将会更加明显,但这是整个其他职位。