Accept ArrayBuffer in web API (C#) sent in Post request via ajax (Without use of form)
Asked Answered
F

1

8

I have a ajax method for uploading file to server . - It sends the ArrayBuffer (Typed array of js from reading a file) to server with 3 more params. Endpoint is written in C# web API application.

Here is my C# endpoint -

public async Task<HttpResponseMessage> UploadFile(string param1, string param2, string fileName, [FromBody] byte[] arrayBuffer)
{
    try
    {         
       var response = await xyz.UploadFile(param1, param2, fileName, arrayBuffer);
       var httpResponse = Request.CreateResponse(HttpStatusCode.Created);
       httpResponse.Content = new StringContent(response, Encoding.UTF8, "application/json");
       return httpResponse;
    }
    catch (Exception e)
    {
        return Request.CreateResponse(HttpStatusCode.InternalServerError, e.ToString());
    }
}

My Question is what should be the type of the arrayBuffer param here in C# so that it get's populated with the binary data I sent in request from js.

Same request sent to Sharepoint's Rest API creates the file, I have already checked request is correct. Only problem is My endpoint is not able to match the data sent in RequestBody to it's param.

EDIT

For now we have changed the content to base64 string. Couldn't work on trying new things as we had to deliver. If anyone comes here with same problem Probably you will also have to do the same.

Fairlead answered 17/1, 2020 at 12:4 Comment(4)
If you are using ASP.NET Core (as your tag suggest), then using the IFormFile Interface should allow you to retrieve the uploaded file : learn.microsoft.com/en-us/aspnet/core/mvc/models/…Alban
Sorry not using Core, it's only ASP with MVCFairlead
Can you share your request payload? Are you sure it isn't multipart/form-data?Eusebioeusebius
Try looking at the request in a proxy like Fiddler.Potentilla
M
1

you can use HttpPostedFileBase to read binary

public async Task<HttpResponseMessage> UploadFile(string param1, string param2, string fileName, [FromBody] HttpPostedFileBase  arrayBuffer)
{

     arrayBuffer.InputStream
Marlenmarlena answered 24/1, 2020 at 19:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.