.net上传图片以base64格式传图片,预览,美化file控件

只有点保存时候,到后台了,才把图片保存到服务器上

前台代码

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>编辑</title>
    <link href="/JS/layui/css/layui.css" rel="stylesheet" />
    <link rel="stylesheet" href="/CSS/layuiadmin.css" />
    <script src="/JS/jquery-3.4.1.js"></script>
    <script src="/JS/layui/layui.all.js"></script>
    <style>
        .file {
            position: relative;
            display: inline-block;
            background: #D0EEFF;
            border: 1px solid #99D3F5;
            border-radius: 4px;
            padding: 4px 12px;
            overflow: hidden;
            color: #1E88C7;
            text-decoration: none;
            text-indent: 0;
            line-height: 20px;
        }

            .file input {
                position: absolute;
                font-size: 100px;
                right: 0;
                top: 0;
                opacity: 0;
            }

            .file:hover {
                background: #AADFFD;
                border-color: #78C3F3;
                color: #004974;
                text-decoration: none;
            }
    </style>
</head>
<body>
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body" style="padding: 15px;">
                <div class="layui-form-item">
                    <label class="layui-form-label">标题</label>
                    <div class="layui-input-block">
                        <input type="text" id="title" lay-verify="title" autocomplete="off" placeholder="请输入标题" class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">请选择图片</label>
                    <div class="layui-input-block">
                        <a href="javascript:;" class="file">选择文件<input type="file" name="" id="image" /></a>
                        <img src="" id="image_show" />
                    </div>
                </div>
                <div class="layui-form-item layui-layout-admin">
                    <div class="layui-input-block">
                        <div class="layui-footer" style="left: 0;">
                            <button class="layui-btn sim_btn">立即提交</button>
                            <input type="button" id="btnReset" class="layui-btn layui-btn-primary" value="重置" />
                        </div>
                    </div>
                </div>


            </div>
        </div>
    </div>
    <script type="text/javascript">
        var layer, form, laypage, laydate, upload;

        $(function () {
            layui.use(['layer', 'form', 'laypage', 'laydate', 'upload', 'jquery'], function () {
                layer = layui.layer;
                form = layui.form;
                laypage = layui.laypage;
                laydate = layui.laydate;
                upload = layui.upload;
                var $ = layui.jquery;
            });
            //提交表单
            $("body").on("click", ".sim_btn", function () {
                saveData();
            });
            //清空文件框
            $("body").on("click", "#btnReset", function () {
                $(":input[type='text']").val("");
            });
            $("#image").change(function () {
                var file = $("#image").get(0).files[0];
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function (e) {
                    // 图片格式为 base64
                    //console.log(e)
                    $("#image_show").attr("src", e.target.result);
                }
            });

        });
        function saveData() {

            var errorMsg = "";
            var title = $("#title").val();
            var imgurl = $("#image_show").attr("src");//$(".image").val();

            if (title == "") {
                errorMsg = "请输入标题";
            }
            //if (imgurl == "") {
            //    errorMsg = "请选择图片";
            //}
            if (errorMsg != "") {
                layer.msg(errorMsg, { icon: 7 });
                return false;
            }
            //return false;?act=AddData
            loadIndex = layer.load(0);
            var url = "Banner_ADD.aspx";
            $.ajax({
                type: "POST",
                url: url,
                dataType: "JSON",
                //contentType: "application/x-www-form-urlencoded",
                data: { act: 'AddData', title: title, imgurl: imgurl },
                success: function (result) {
                    if (result.State) {
                        layer.close(loadIndex);
                        layer.msg("操作成功", { time: 3000 });
                    }
                    else {
                        layer.msg(result.ErrorMsg, { time: 3000 });
                    }
                }, complete: function (result) {
                    layer.close(loadIndex);
                }
            });
        }


    </script>

</body>
</html>

后台代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Common;
using DAL;
using Model;
using System.Drawing;
namespace MyProject
{
    public partial class Banner_ADD : System.Web.UI.Page
    {
        private string act = string.Empty;
        private BannerInfoBLL bannerInfoBLL;
        private BannerInfoModel bannerInfoModel;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request["act"]))
                {
                    act = Request["act"];
                }
                switch (act)
                {
                    case "AddData":
                        int id = Convert.ToInt32(Request["key"]);
                        string strtitle = Request["title"];//
                        string imgurl = Request["imgurl"];//
                        AddData(id, strtitle, imgurl);
                        break;
                    default:
                        //PageLoad();
                        break;
                }


            }
        }

        private void AddData(int id, string strtitle, string imgurl)
        {
            string base64 = imgurl.Split(',')[1];//规范化,逗号前面的是标识符,用于说明原图片的名字和格式
            string path = Server.MapPath("/");//获取网站的根路径
            string strRand = PublicHelper.RanStr(10,true);
            string strSuffix = ".jpg"; //文件的后缀名根据实际情况
            string strPath = path + "\\UploadFile\\" + DateTime.Now.ToString("yyyyMMdd") + strRand + strSuffix;
            string strFilePath = DateTime.Now.ToString("yyyyMMdd") + strRand + strSuffix;
            MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64));
            Bitmap bit = new Bitmap(stream);
            bit.Save(strPath);//保存图片到本地

            int iresult = 0;
            ResultInfo resultInfo = new ResultInfo() { State = false };
            StringBuilder sbWomanName = new StringBuilder();
            if (!string.IsNullOrEmpty(strtitle) && !string.IsNullOrEmpty(strFilePath))
            {
                bannerInfoBLL = new BannerInfoBLL();
                bannerInfoModel = new BannerInfoModel();
                if (id > 0)
                {
                    bannerInfoModel = bannerInfoBLL.GetModel(" and id =" + id);
                }
                bannerInfoModel.Titles = strtitle;
                bannerInfoModel.ImageURL = strFilePath;
                if (id > 0)
                {
                    iresult = bannerInfoBLL.UpdateData(bannerInfoModel);
                }
                else
                {
                    iresult = bannerInfoBLL.AddData(bannerInfoModel);
                }
                if (iresult > 0)
                {
                    resultInfo.Data = iresult.ToString();
                    resultInfo.State = true;
                }


                string resultJson = JsonHelper.ObjectToJSON(resultInfo);
                Response.Write(resultJson);
                Response.End();
            }

        }


    }
}

posted @   离。  阅读(205)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示