嘗試像這樣用ajax/JavaScript的...這將使用AJAX數據參數發佈的base64字符串控制器作爲datauri參數傳遞給控制器。
MyFunc會將圖像轉換爲base64並將其發佈到一個動作。
function MyFunc() {
con.drawImage(v, 0, 0, canvasWidth, canvasHeight);
var = document.getElementById('imgprvw');
dataURL = c.toDataURL('image/png');
var raw_image_data = dataURL.replace(/^data\:image\/\w+\;base64\,/, '');
$.ajax({
url: '@PathHelper.FullyQualifiedApplicationPath(Request)' + 'MySaveController/MySaveAction',
type: 'POST', dataType: 'json',
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
data:
{
datauri: JSON.stringify(raw_image_data),
},
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
alert('Image Saved');
}
});
}
在控制器中... MySaveAction會將base64轉換爲位圖並保存。
public ActionResult MySaveAction(string datauri)
{
// Some stuff.
if (datauri.Length > 0)
{
Byte[] bitmapData = new Byte[datauri.Length];
bitmapData = Convert.FromBase64String(FixBase64ForImage(datauri));
string fileLocationImageName = "C:/MYIMAGE.JPG";
MemoryStream ms = new MemoryStream(bitmapData);
using (Bitmap bitImage = new Bitmap((Bitmap)Image.FromStream(ms)))
{
bitImage.Save(fileLocationImageName, System.Drawing.Imaging.ImageFormat.Jpeg);
output = fileLocationImageName;
}
}
return Json(output, JsonRequestBehavior.AllowGet);
}
輔助方法...這將給出ajax url參數所需的請求的全限定路徑。
public static class PathHelper
{
public static string FullyQualifiedApplicationPath(HttpRequestBase httpRequestBase)
{
string appPath = string.Empty;
if (httpRequestBase != null)
{
//Formatting the fully qualified website url/name
appPath = string.Format("{0}://{1}{2}{3}",
httpRequestBase.Url.Scheme,
httpRequestBase.Url.Host,
httpRequestBase.Url.Port == 80 ? string.Empty : ":" + httpRequestBase.Url.Port,
httpRequestBase.ApplicationPath);
}
if (!appPath.EndsWith("/"))
{
appPath += "/";
}
return appPath;
}
}
最後,這是對base64字符串的修復...即刪除使用JSON.Stringify轉換base64時插入的垃圾。
public string FixBase64ForImage(string image)
{
System.Text.StringBuilder sbText = new System.Text.StringBuilder(image, image.Length);
sbText.Replace("\r\n", String.Empty);
sbText.Replace(" ", String.Empty);
sbText.Replace("\"", String.Empty);
return sbText.ToString();
}
將文件上傳到服務器然後將其轉換爲base64將會更容易。 –
我使用ajax窗體,所以我不能使用HttpPostedFileBase,也在控制器中我得到'imageValue'的一個非常大的字符串的值 –