用AJAX文件上传到dotnet Core

时间:2017-03-08 18:15:31

标签: javascript ajax file-upload .net-core

我尝试将文件上传到.net核心控制器方法但我的文件'触发控制器时参数为null。这是服务器端代码......

    [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"));
    }

该路线被触发正常,但是&#39; file&#39;是空的。

我认为这个问题可能与客户端相关,因为在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
        });
    }
}

&#39; fileUpload&#39;使用目标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
{}

以上我希望不会显示表单数据吗?

1 个答案:

答案 0 :(得分: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调用,这将更加明显,但这是另一篇文章。