Using FormData API
If you use FormData, you can send image either as blob or string. Both the options are specified in this example.
To send image as blob
formData.append("image", $("#image").get(0).files[0])
To send image as string
use FileReader.readAsDataURL
UI
A simple form with a name input and a file control to upload an image
<form>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
</div>
<div class="form-group">
<label for="image">File input</label>
<input type="file" id="image" onchange='openFile(event)'>
</div>
<img id='output' style="height:100px; width:100px;">
<button type="button" id="submitForm" class="btn btn-default">Submit as FormData</button>
<button type="button" id="submitFormJson" class="btn btn-default">Submit as JSON</button>
</form>
Script
The image is displayed in the browser when the file is selected by setting the src attribute of image to Filereader.result. Also the base64 prefix is removed when setting the imageData variable which is later appended to the formdata.
var imageData;
function openFile(e) {
var input = e.target;
var reader = new FileReader();
reader.onload = function () {
var dataURL = reader.result;
var output = document.getElementById('output');
//set image src
output.src = dataURL;
//remove base64 keyword while uploading
imageData = dataURL.split("base64,")[1];;
};
reader.readAsDataURL(input.files[0]);
}
$("#submitForm").click(function () {
var formData = new FormData();
formData.append("name", $("#name").val());
//send image as blob
formData.append("image", $("#image").get(0).files[0])
//send image as base64 string
formData.append("imageData", imageData);
$.ajax({
type: "post",
url: "/upload/index",
contentType: false,
processData: false,
data: formData,
success: function (data) {
},
error: function () {
}
});
})
Model
The image is specified as HttpPostedFileBase type
public class UploadFileModel
{
public string Name { get; set; }
public HttpPostedFileBase Image { get; set; }
public string ImageData { get; set; }
}
Controller
Convert the base64 encode image string to byte and save it in the file
[HttpPost]
public ActionResult Index(UploadFileModel model)
{
var filePath = Server.MapPath("~/Images/happy-new-year.jpg");
// Saving base64 string image
System.IO.File.WriteAllBytes(filePath, Convert.FromBase64String(model.ImageData));
// Saving binary image (HttpPostedFileBase)
model.Image.SaveAs(filePath);
return View();
}
Using JSON
If you want to send JSON data, you can send the image as base64 encoded string using FileReader.readAsDataURL. In this approach you can include additional data also
Script
var imageData;
function openFile(e) {
var input = e.target;
var reader = new FileReader();
reader.onload = function () {
var dataURL = reader.result;
var output = document.getElementById('output');
output.src = dataURL;
imageData = dataURL.split("base64,")[1];;
};
reader.readAsDataURL(input.files[0]);
}
$("#submitFormJson").click(function () {
var jsonData = {
name: $("#name").val(),
imageData: imageData,
categories: [{ id: 1, name: "cat1" }, { id: 2, name: "cat2" }]
};
$.ajax({
type: 'post',
url: '/upload/index',
data: JSON.stringify(jsonData),
contentType: "application/json; charset=utf-8",
success: function (data) {
},
error: function () {
alert("there was error uploading files!");
}
});
})
Model
public class UploadFileModel
{
public string Name { get; set; }
public string ImageData { get; set; }
public Category[] Categories { get; set; }
}
public class Category
{
public string Id { get; set; }
public string Name { get; set; }
}
Controller
[HttpPost]
public ActionResult Index(UploadFileModel model)
{
var filePath = Server.MapPath("~/Images/happy-new-year.jpg");
// Saving base64 string image
System.IO.File.WriteAllBytes(filePath, Convert.FromBase64String(model.ImageData));
return View();
}