排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256
50010702506256
欢迎加群交流技术
分类:
.NET MVC
前台
<div> <input type="file" onchange="selectImage(this.files)" accept=""> </div>
js:
function selectImage(files) {
let reader = new FileReader();
let file = files[0];
reader.readAsDataURL(file);
reader.onload = function () {
$.post('/Home/UpLoadFile', { filecontent: reader.result }, function (result) {
alert("传递成功!");
});
}
}后台:
public ActionResult UpLoadFile()
{
string base64 = Request.Form["filecontent"];
//base64需要把前面的申明去掉
string newbase = base64.Replace("data:image/jpeg;base64", "");
base64TOImg(newbase);
return View();
}后台去掉前缀的方法换成正则表达式,因为格式不固定
/// <summary>
/// base64图片上传
/// </summary>
public void UpLoadFile()
{
string base64 = Request.Form["filecontent"];
string fileExt = Request.Form["fileExt"];
#region base64需要把前面的申明去掉(当然前缀这个也可以放在前端处理)
//string newbase = base64.Replace("data:image/jpeg;base64,", "");
//这里用了一下正则表达式因为可能是格式data:image/jpeg;base64,data:image/png;base64等等
string base64img = Regex.Replace(base64, "data:image/.*;base64,", "");
#endregion
}存储图片:
private void base64TOImg(String base64str)
{
Byte[] streamByte = Convert.FromBase64String(base64str);
System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte);
string filename = Server.MapPath("~/upload/" + Guid.NewGuid().ToString().Replace("-", "") + ".jpg");
try
{
byte[] buffer = Convert.FromBase64String(base64str);
FileStream fs = new FileStream(filename, FileMode.CreateNew);
fs.Write(buffer, 0, buffer.Length);
fs.Close();
}
catch (Exception ex)
{
throw ex;
}
}欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)
评价