Web API分段上传FileData始终为空,FormData popuplated

时间:2013-01-30 07:00:21

标签: ajax asp.net-web-api

我刚刚进入Web API并试图获得以下方法为我工作,但似乎provider.FileData总是出现空(count = 0)但是provider.FormData似乎过去没有问题。我无法弄清楚为什么会这样。

public async Task<HttpResponseMessage> PostFormData()
{
    // Check if the request contains multipart/form-data.
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    string root = HttpContext.Current.Server.MapPath("~/App_Data");
    var provider = new MultipartFormDataStreamProvider(root);

    try
    {
        // Read the form data.
        await Request.Content.ReadAsMultipartAsync(provider);

        // This illustrates how to get the file names.
        foreach (MultipartFileData file in provider.FileData)
        {
            Trace.WriteLine(file.Headers.ContentDisposition.FileName);
            Trace.WriteLine("Server file path: " + file.LocalFileName);
        }
        return Request.CreateResponse(HttpStatusCode.OK);
    }
    catch (System.Exception e)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}

我从以下

调用方法
    uploader.bind('FileUploaded', function (up, file) {
            $('#' + file.id + " b").html("100%").css({ 'color': '#47C449' });
            $('#' + file.id).css({ 'background-color': '#F7FFF7' });
            var data = new FormData();

            data.append('file-', file.id);
            data.append('filename', file.name);
            data.append('Size', file.size);

            $.ajax({
                url: sf.getServiceRoot('mysite') + "upload/PostFormData",
                type: "POST",
                data: data,
                contentType: false,
                processData: false,
                beforeSend: sf.setModuleHeaders
            }).done(function (response, status) {
                alert(response);
            }).fail(function (xhr, result, status) {
                alert("error: " + result);
            });
        });

1 个答案:

答案 0 :(得分:0)

试试这样:

uploader.bind('FileUploaded', function (up, file) {
    $('#' + file.id + " b").html("100%").css({ 'color': '#47C449' });
    $('#' + file.id).css({ 'background-color': '#F7FFF7' });
    var data = new FormData();
    data.append('file', file);

    var uri = sf.getServiceRoot('mysite') + 'upload/PostFormData';
    var xhr = new XMLHttpRequest();
    xhr.open('POST', uri, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText); // handle response.
        }
    };
    xhr.send(data);
});