[英]How to upload blob and convert to image in webapi
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. 我正在尝试将从映像创建的Blob上传到我的服务器,然后将Blob转换为映像并将其保存在C#webapi中。 I created a canvas to store my image and the converted it into a base64 file.
我创建了一个画布来存储图像并将其转换为base64文件。 Below is my javascript code.
以下是我的JavaScript代码。
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#. 下面是我在C#中的webapi服务器代码。 The file is saved as "thisimage.jpg" as appended in my FormData in javascript.
该文件另存为“ thisimage.jpg”,并附加在JavaScript的FormData中。
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;
}
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.
因此,现在可以使用了,这是如何使用Webapi和javascript将Blob上传到服务器的示例。 I added a string value id to my post and used that to give the file a name.
我在帖子中添加了一个字符串值id,并使用它来给文件起一个名字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.