Friday, August 24, 2018

ajax POST file to WebAPI, file is corrupted

Hello,

I am probably having a simple problem, but I have looked at this too long.

I am writing an office add-in. One of the functions of this add-in is to post the file to the server.

The issue is that on the client, before I send the file it is about 12K. When it reaches the server, it is ~40K.

What is puzzling to me is that no matter which file I send on the client size, the Content-Length of the request is always the ~40K.

Any ideas anyone?

Here is some of the code:

Client

function onGotAllSlices(docdataSlices) { var docdata = []; for (var i = 0; i < docdataSlices.length; i++) { docdata = docdata.concat(docdataSlices[i]); } if (window.FormData !== undefined) { var data = new FormData(); data.append(fileName, docdata); // docdata.length = 12532 $.ajax({ type: "POST", url: "../../api/Populate/test", contentType: false, processData: false, data: data, cache: false, success: function (result) { console.log(result); window.open(result, "_blank"); }, error: function (xhr, status, p3, p4) { var err = "Error " + " " + status + " " + p3 + " " + p4; if (xhr.responseText && xhr.responseText[0] === "{") err = JSON.parse(xhr.responseText).Message; console.log(err); } }); } else { alert("This browser doesn't support HTML5 file uploads!"); } } 

Server

 [RoutePrefix("api/Populate")] public class FormPopulationController : ApiController { [Route("Test")] [HttpPost()] public async Task<HttpResponseMessage> TestForm() { // 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 MultipartFileStreamProvider(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); byte[] buff = FileToByteArray(file.LocalFileName); // WTF - Here buff.Length = 40714???? // // Delete the file File.Delete(file.LocalFileName); } return Request.CreateResponse(HttpStatusCode.OK); } catch (System.Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } } private byte[] FileToByteArray(string fileName) { return File.ReadAllBytes(fileName); } } 

Thanks in advance.

ajax POST file to WebAPI, file is corrupted Click here
  • Blogger Comment
  • Facebook Comment

0 comments:

Post a Comment

The webdev Team