Reputation: 923
I am trying to upload a blob created from an image to my server and then convert the blob to an image and save it in a C# webapi. I created a canvas to store my image and the converted it into a base64 file. Below is my javascript code.
var blob = canvas.toDataURL("image/jpeg"); // This will save your image as a
//jpeg file in the base64 format.
var jpegFile64 = blob.replace(/^data:image\/(png|jpeg);base64,/, "");
var jpegBlob = base64ToBlob(jpegFile64, 'image/jpeg');
var data = new FormData();
data.append("mypic", jpegBlob, "thisimage.jpg");
var oReq = new XMLHttpRequest();
oReq.open("POST", "http://localhost:52704/api/uploadfile/myfile.jpg/", true);
oReq.onload = function (oEvent) {
alert(this.responseText);
};
oReq.send(data);
}
function base64ToBlob(base64, mime) {
mime = mime || '';
var sliceSize = 1024;
var byteChars = window.atob(base64);
var byteArrays = [];
for (var offset = 0, len = byteChars.length; offset < len; offset += sliceSize) {
var slice = byteChars.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, { type: mime });
}
Below is my webapi server code in C#. The file is saved as "thisimage.jpg" as appended in my FormData in javascript.
public string Post(string id)
{
string result = null;
var httpRequest = HttpContext.Current.Request;
string count = httpRequest.Files.Count.ToString();
if (httpRequest.Files.Count > 0)
{
var postedFile = httpRequest.Files[0];
var filePath = "c:/inetpub/wwwroot/pics/" + postedFile.Filename;
postedFile.SaveAs(filePath);
// File is saved as "thisimage.jpg"
result = "File saved as " + filePath;
}
else
{
result = "Upload failed";
}
return result;
}
Upvotes: 2
Views: 5459
Reputation: 923
It now works! I had a typo in my postedfile address. So now it works and this is an example of how to upload a blob to a server using Webapi and javascript. I added a string value id to my post and used that to give the file a name.
Upvotes: 1