1

我刚刚进入 Web API 并试图让以下方法为我工作,但似乎 provider.FileData 总是空的(计数 = 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);
            });
        });
4

1 回答 1

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);
});
于 2013-01-30T07:07:56.110 回答