故如虹,知恩;故如月,知明
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术

.net base64上传图片

4837人阅读 2019/8/28 23:24 总访问:3935627 评论:0 收藏:0 手机
分类: .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;
    }
}



欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739

评价