Stilgar
Stilgar

Reputation: 23551

How to AJAX POST file contents together with other data to ASP.NET Web API

I want to create a form where the user adds some information (text in inputs, selects, etc.) and uploads a file. For example if I have a Product entity that looks like this

public class Product
{
    public string Name { get; set; }
    public byte[] ProductImage { get; set; }
}

I want to do a POST via AJAX to a Web API action that looks like this

public void Post(Product product)

I want the name string and the bytes to be sent together. I don't want to upload the file in advance.

What should I do on the client to send the data preferably as JSON. One thing that seems easy is make ProductImage a string and send base64 encoded data which is easy to read with the FileReader API but is this the correct way? It seems cleaner to have the data map to a byte array which it actually is.

Upvotes: 1

Views: 282

Answers (1)

Stilgar
Stilgar

Reputation: 23551

We ended up base64 encoding the file and sending it as part of the JSON then parsing it on the server into a byte array. One should be careful when allowing upload of large files but for small files it seems to be fine.

Upvotes: 1

Related Questions