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

net core base64上传图片

6172人阅读 2019/8/30 11:53 总访问:3837670 评论:2 收藏:0 手机
分类: .NET Core

前台

html:

<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) {
        });
    }
}


后端

base64转化的工具类:

public class Base64Convert
    {
        /// <summary>
        /// 文件转换成Base64字符串
        /// </summary>
        /// <param name="fileName">文件绝对路径</param>
        /// <returns></returns>
        public static String FileToBase64(string fileName)
        {
            string strRet = null;

            try
            {
                FileStream fs = new FileStream(fileName, FileMode.Open);
                byte[] bt = new byte[fs.Length];
                fs.Read(bt, 0, bt.Length);
                strRet = Convert.ToBase64String(bt);
                fs.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return strRet;
        }

        /// <summary>
        /// Base64字符串转换成文件
        /// </summary>
        /// <param name="strInput">base64字符串</param>
        /// <param name="fileName">保存文件的绝对路径</param>
        /// <returns></returns>
        public static bool Base64ToFileAndSave(string strInput, string fileName)
        {
            bool bTrue = false;

            try
            {
                byte[] buffer = Convert.FromBase64String(strInput);
                FileStream fs = new FileStream(fileName, FileMode.CreateNew);
                fs.Write(buffer, 0, buffer.Length);
                fs.Close();
                bTrue = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return bTrue;
        }
    }

提交的控制器:

public IActionResult UpLoadFile()
{
    string base64 = Request.Form["filecontent"];
    //base64需要把前面的申明去掉
    string newbase = base64.Replace("data:image/jpeg;base64,", "");
    //把图片存储到c盘,具体操作的时候位置可以自行改变
    Base64Convert.Base64ToFileAndSave(newbase, "c://timg.jpg");

    return View();
}


优化一下

前台的时候把图片后缀名传过去

<script>
    function selectImage(files) {
        let reader = new FileReader();
        let file = files[0];
        console.log(file);

        //取出来文件的后缀名(方便在后台保存的时候用)
        var index = file.name.lastIndexOf(".");
        var fileExt = file.name.substr(index + 1);
        console.log(fileExt);

        reader.readAsDataURL(file);
        reader.onload = function () {
            console.log(reader.result);
            $.post('/Home/UpLoadFile', { filecontent: reader.result, fileExt: fileExt }, function (result) {
            });
        }
    }
</script>

后台去掉前缀的方法换成正则表达式,因为格式不固定

/// <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
}

保存的时候图片名字用guid

//把图片存储到c盘,具体操作的时候位置可以自行改变
Base64Convert.Base64ToFileAndSave(base64img, "c://" + Guid.NewGuid().ToString().Replace("-", "") +"."+ fileExt);









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

评价