3

I am trying to pass a image dat to a web API method using example code I found on here http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2 and I am finding that MultipartFormDataStreamProvider.FileData is always empty. Why might this be? Also, is this the right approach to be taking? Are there options? I am trying to pass only a single image.

The Call

var t = new FormData();
t.append('file-', file.id);
t.append('filename', file.name);
t.append('Size', file.size);

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

});

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);
        }
    }
4

1 回答 1

0

通过表单发布时,我可以正确获取 fileData,

如示例中的@WebAPI 上传错误。MIME 多部分流的预期结束。MIME 多部分消息不完整

祝你好运,

于 2014-04-17T08:28:28.700 回答