我正在尝试将从图像创建的blob上传到我的服务器,然后将blob转换为图像并将其保存在C#webapi中。我创建了一个画布来存储我的图像并将其转换为base64文件。以下是我的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 });
}
下面是我在C#中的webapi服务器代码。该文件保存为&#34; thisimage.jpg&#34;在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;
}
答案 0 :(得分:0)
它现在有效!我的发布文件地址中有拼写错误。所以现在它可以工作,这是一个如何使用Webapi和javascript将blob上传到服务器的示例。我在帖子中添加了一个字符串值id,并使用它来为文件命名。