Posting image data from Ajax to WebAPI

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

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

      

+3


source to share


1 answer


I could get fileData correctly if you submitted via the form,

as in the example goes @ WebAPI loading error. The expected end of the multipoint MIME stream. MIME message not complete



Luck,

0


source