使用base64上传图片
1、前台
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm4.aspx.cs" Inherits="Lian.WebForm4" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <div id="uploadselect" class="uploadselect"> <input type="file" id="upload" class="upload" accept="image/*" /> </div> <asp:HiddenField ID="hfAvatar" runat="server" /> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> </div> </form> </body> <script src="lib/lrz/dist/lrz.bundle.js"></script> <script> document.querySelector('#upload').addEventListener('change', function () { lrz(this.files[0], { width: 300, height: 300 }) .then(function (rst) { // 上传文件数据 var xhr = new XMLHttpRequest(); xhr.open('POST', 'yiban/ImageUploadHandler.ashx?length=' + rst.base64Len); // onload请求成功获取数据成功 xhr.onload = function () { if (xhr.status === 200) { document.getElementById('BodyContent_hfAvatar').value = xhr.responseText; } else { alert('图片上传失败!'); } }; //send[send] (森的)()方法,发送具体请求 xhr.send(rst.base64); // 在页面中显示图片 var img = new Image(); img.src = rst.base64; img.width = 100; img.height = 100; document.getElementById('uploadselect').parentNode.appendChild(img); document.getElementById('uploadselect').remove(); // 返回对象 return rst; }) .catch(function (err) { console.log(err); alert('图片上传失败!'); }); }); </script> </html>
2、一般处理程序
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.SessionState; namespace Lian.yiban { /// <summary> /// ImageUploadHandler 的摘要说明 /// </summary> public class ImageUploadHandler : IHttpHandler,IRequiresSessionState { public void ProcessRequest(HttpContext context) { int length = int.Parse(context.Request.QueryString["length"] ?? "0"); if (length <= 0) { context.Response.StatusCode = 400; context.Response.End(); return; } // 读取编码流长度 int rsLen = (int)context.Request.InputStream?.Length; if (rsLen <= 0) { context.Response.StatusCode = 400; context.Response.End(); return; } // 尝试存储 byte[] base64Bytes = new byte[context.Request.InputStream.Length]; context.Request.InputStream.Seek(0, SeekOrigin.Begin); context.Request.InputStream.Read(base64Bytes, 0, base64Bytes.Length); string base64String = Encoding.Default.GetString(base64Bytes); // 判断是否完整接收 if (base64String?.Length == length) { base64String = base64String.Substring(base64String.IndexOf("base64") + 7); byte[] baseByte = Convert.FromBase64String(base64String); // 保存到文件 string randomString = Guid.NewGuid().ToString("N");//全球唯一编码 string fileName = $"{context.Server.MapPath("~/avatar")}/{randomString}.jpg"; string fileUrl = $"/avatar/{randomString}.jpg"; using (MemoryStream memoryStream = new MemoryStream(baseByte)) { using (Image image = Image.FromStream(memoryStream)) { image.Save(fileName, ImageFormat.Jpeg); } } context.Session["aa"] = fileUrl; context.Response.Write(fileUrl); context.Response.End(); } else { context.Response.StatusCode = 400; context.Response.End(); return; } } public bool IsReusable { get { return false; } } } }
3、后台接收数据
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Model; namespace Lian { public partial class WebForm4 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { using (Model1 db = new Model1()) { var a = db.TBUser.FirstOrDefault(b => b.Id == "a1"); a.Avatar = Session["aa"].ToString(); db.SaveChanges(); } } } }