1. 程式人生 > 其它 >使用base64上傳圖片

使用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();
            }

        }
    }
}