标签:
我们来总结一下使用AJAX以POST方式上传图片的方法。
一、普遍的一种是以file的格式请求。在Request.Files中获取文件。
public ActionResult UploadFile(HttpContext request) { HttpPostedFileBase img = Request.Files[0]; string path = AppDomain.CurrentDomain.BaseDirectory + @"Upload/"; img.SaveAs(Path.Combine(path, img.FileName)); return View(); }
二、另一种是通过Json上传64位编码(base64 URL)的图片数据进行保存。
64位编码的图片数据格式一般如下:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABG4AAAH0CAYAAABsCGvoAAAgAElEQVR4Xuy9C5RV1Zmo++96P3ZVURSv4hEEFdQobYKtJESjJME+6WgTpPUQIrfpY8NRui/aKlcvY2hON0fN5TIUbh/6XDs9bgah0+1BY+gk2p2QFpIAgk9AiGBhlQgIokgVRQFVu3bd9S+c21WbXVV71157Pfb+loNh1ar5+Oc3Z/H46p9zRnqsR3ggAAEIQAACEIAABCAAAQhAAAIQgAAEAkcggrgJ3JwQEAQgAAEIQAACEIAABCAAAQhAAAIQsAkgblgIEIAABCAAAQhAAAIQgAAEIAABCEAgoAQQNwGdGMKCAAQgAAEIQAACEIAABCAAAQhAAAKIG9YABCAAAQhAAAIQgAAEIAABCEAAAhAIKAHETUAnhrAgAAEIQAACEIAABCAAAQhAAAIQgADihjUAAQhAAAIQgAAEIAABCEAAAhCAAAQCSgBxE9CJISwIQAACEIAABCAAAQhAAAIQgAAEIIC4YQ1AAAIQgAAEIAABCEAAAhCAAAQgAIGAEkDcBHRiCAsCEIAABCAAAQhAAAIQgAAEIAABCCBuWAMQgAAEIAABCEAAAhCAAAQgAAEIQCCgBBA3AZ0YwoIABCAAAQhAAAIQgAAEIAABCEAAAogb1gAEIAABCEAAAhCAAAQgAAEIQAACEAgoAcRNQCeGsCAAAQhAAAIQgAAEIAABCEAAAhCAAOKGNQABCEAAAhCAAAQgAAEIQAACEIAABAJKAHET0IkhLAhAAAIQgAAEIAABCEAAAhCAAAQggLhhDUAAAhCAAAQgAAEIQAACEIAABCAAgYASQNwEdGI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wDE4AAAAASUVORK5CYII=
可以在html的image标签中直接指定给src。
Ajax上传方法:
var picture = jqplotToImg($(‘#ChartContent‘)); //prompt("", picture); $.ajax({ type: ‘POST‘, url: ‘../Demo/UploadFileJson‘, async: false, data: { source: picture }, success: function (data) { //alert(data); } });
MVC中接收,并保存:
public ActionResult UploadFileJson(JObject request) { string img64Data = request.Value<string>("imgData"); using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(img64Data))) { using (Bitmap img = new Bitmap(ms)) { img.Save("SavingPath" + "ImageName.jpg"); } } return Json("ok"); }
标签:
原文地址:http://www.cnblogs.com/firstdown/p/4452146.html