html代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/Content/js/index.js"></script>
    <style>
        body {
            margin: 0px;
            background-color: #F5F5F5;
        }

        h1 {
            background-color: #3D83D9;
            margin: 0px;
            height: 40px;
        }

        .div-gap {
            margin: 20px;
            background-color: #FFFFFF;
        }
        .div-bgNo {
            margin: 20px;
        }
        .div-border {
            border: 5px;
            border-radius: 5px;
        }

        .h200 {
            height: 200px;
        }

        input {
            border: 0px;
            width: 100%;
            height: 30px;
        }

        button {
            background-color: #0074BA;
            margin: 00px;
            width: 100%;
            height: 30px;
            padding: 0px;
        }
    </style>
</head>
<body>
    <h1></h1>
    <div>
        <!--1.输入框区域-->
        <div>
            <form id="j_form">
                <input type="reset" style="display:none;" />
                <div class="div-bgNo">
                    <label>亲爱的:<span>莫负韶华</span></label>
                </div>
                <div class="div-gap div-border h200">
                    <input name="userMessage" placeholder="请在这里直接填写你的问题或意见建议,谢谢">
                    <div style="margin-top:40px;margin-left:15px">
                        <img id="imgIdCard" style="width:100px;height:100px;border:0px" src="~/Content/image/add.png">
                        <input name="userLogo" id="urlIdCard" type="hidden" />
                        <input type="file" value="123456" id="btnIdCard" style="display:none" />
                        <div>上传照片</div>
                    </div>
                </div>
                <div class="div-gap">
                    <input name="userStore" placeholder="请选择门店">
                </div>
                <div class="div-gap">
                    <input name="userPhone" placeholder="请输入联系方式">
                </div>
            </form>
        </div>
        <!--2.按钮区域-->
        <div class="div-gap">
            <button id="j_sub">提交</button>
        </div>
    </div>

</body>

</html>

js文件代码

//一.这里使用立即函数都一些方法进行封装
//访问入口为变量:myUitls
(function (w) {
    //一.封装核心对象
    var mainUtil = {
        init: function () {
            this.initLoad();
            this.initEvent();
        },
        initLoad:function(){
            var input = document.getElementById("btnIdCard");
            if (typeof (FileReader) === 'undefined') {
                input.setAttribute('disabled', 'disabled');
            } else {
                input.addEventListener('change',methodUtil.readFile, false);
            }
        },
        initEvent: function () {
            //1.上传图片事件
            $('#imgIdCard').on('click', function () {
                var input1 = document.getElementById("btnIdCard");
                input1.click();
            });

            //2.提交按钮
            $("#j_sub").on('click', function () {
                //1.获取数据
                $.ajax({
                    type: "Post",
                    url: "/Home/SaveData",
                    data: methodUtil.serializeObject($("#j_form")),
                    success: function (data) {
                        if (data.status == '2') {
                            alert("提交成功")
                            $("input[type=reset]").trigger("click");
                        }
                        else {
                            alert("提交失败")
                        }
                    }
                });
            })

        },
    }
    /*********************************一.方法实现**********************************/
    var methodUtil = {
        //1.上传图片文件
        readFile: function () {
            var file = this.files[0];
            //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
            if (!/image\/\w+/.test(file.type)) {
                alert("请确保文件为图像类型");
                return false;
            }
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                $.ajax({
                    type: "Post",
                    url: "/Home/UploadAppImg",
                    data: {
                        imgStr: this.result,
                    },
                    success: function (data) {
                        if (data.status == '1') {
                            var url = data.message1;
                            document.getElementById("imgIdCard").src = url;
                            document.getElementById("urlIdCard").value = url;
                        }
                        else {
                            alert("上传失败")
                        }
                    }
                });
            }
        },
        //2.表单
        serializeObject: function (form) {
            var o = {};
            $.each(form.serializeArray(), function (intdex) {
                if (o[this['name']]) {
                    o[this['name']] = o[this['name']] + "," + this['value'];
                } else {
                    o[this['name']] = this['value']
                }
            });
            return o;
        }
    }

    w.mainUtil = mainUtil;
})(window);

$(function () {
    mainUtil.init();

})

后台图片处理

 #region 1.保存用户图片
        /// <summary>
        /// 保存用户图片
        /// </summary>
        /// <param name="imgStr">图片文件Base64字符串</param>
        /// <returns></returns>
        public ActionResult UploadAppImg(string imgStr)
        {
            try
            {
                if (imgStr.Length > 22)
                {
                    if (imgStr.Contains("data:image/jpeg;base64"))
                    {
                        imgStr = imgStr.Substring(23).Replace("\n\r", "");
                    }
                    else
                    {
                        imgStr = imgStr.Substring(22).Replace("\n\r", "");
                    }
                }
                else
                {
                    return Json(new
                    {
                        status = "0",
                        promptInfor = "上传失败"
                    });
                }
                string[] ret = ToImage(null, null, imgStr);
                if (ret[0] == "Success")
                {
                    string relativePath = Path.Combine("/Upload\\ShopImg\\", ret[1]);
                    return Json(new
                    {
                        status = "1",
                        message1 = relativePath,
                        promptInfor = "上传成功",
                    });
                }
                else
                {
                    return Json(new
                    {
                        status = "0",
                        promptInfor = "上传失败"
                    });
                }
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    status = "0",
                    promptInfor = "上传失败"
                });
            }
        }
        #endregion

        #region 2.图片转换
        /// <summary>
        /// 图片转换
        /// </summary>
        /// <param name="ObjFilePath">图片文件路径</param>
        /// <param name="filename">图片文件名称</param>
        /// <param name="filestring">图片文件Base64字符串</param>
        /// <returns></returns>
        private string[] ToImage(string ObjFilePath, string filename, string filestring)//文件到流的转换
        {
            string[] result = { "0", "0" };
            if (string.IsNullOrEmpty(ObjFilePath))
            {
                //ObjFilePath = Server.MapPath(@"..\Upload\ShopPhoto\");//目标图片路径
                string basePath = Server.MapPath(Request.ApplicationPath);
                //上传路径
                ObjFilePath = Path.Combine(basePath, "Upload\\ShopImg\\");
            }
            if (string.IsNullOrEmpty(filename))
            {
                filename = string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now) + ".jpg";
            }
            else
            {
                filename += ".jpg";
            }
            if (Directory.Exists(ObjFilePath) == false)
            {
                Directory.CreateDirectory(ObjFilePath);
            }
            byte[] photo;

            #region
            if (string.IsNullOrEmpty(filestring))
            {
                filestring = “";//这里要做空值验证使用时请写入一个base64字符
            }
            #endregion

            photo = Convert.FromBase64String(filestring);
            MemoryStream ms = new MemoryStream(photo);
            Bitmap bmp = new Bitmap(ms);

            bmp.Save(ObjFilePath + filename, System.Drawing.Imaging.ImageFormat.Jpeg);
            ms.Close();
            result[0] = "Success";
            result[1] = filename;

            return result;
        }
        #endregion

一个原生input上传图片记录的更多相关文章

  1. 自定义input上传图片组件

    自定义input上传图片组件,美化样式 前段时间因为项目需求,做过一个上传图片组件,这里分享下大致思路,希望对有需要的童鞋有所帮助~~~ 功能需求:1.上传图片限制大小.分辨率.类型 2.上传图片支持 ...

  2. pwnable.kr input解题记录

    pwnable input解题记录 给了源码如下: #include "stdio.h" #include "unistd.h" #include " ...

  3. SQL 拼接多个字段的值&一个字段多条记录的拼接 [轉]

    例如student表: studentID studentName studentScore 01 Alice 90 02 Bill 95 03 Cindy 100 一.拼接多个字段的值 select ...

  4. SQL 拼接多个字段的值&一个字段多条记录的拼接

    如student表: studentID studentName studentScore 01 Alice 90 02 Bill 95 03 Cindy 100 一.拼接多个字段的值 select ...

  5. 运用Spring Aop,一个注解实现日志记录

    运用Spring Aop,一个注解实现日志记录 1. 介绍 我们都知道Spring框架的两大特性分别是 IOC (控制反转)和 AOP (面向切面),这个是每一个Spring学习视频里面一开始都会提到 ...

  6. 现有有N个学生的数据记录,每个记录包括学号、姓名、三科成绩。 编写一个函数input,用来输入一个学生的数据记录。 编写一个函数print,打印一个学生的数据记录。 在主函数调用这两个函数,读取N条记录输入,再按要求输出。 N<100

    #include <iostream> using namespace std; struct student {char num[100];  char name[100];  int ...

  7. 原生js上传图片遇到的坑(axios封装)

    后台给我写了一个上传图片的接口,自己用form表单测试成功 接口可以正常跳转 测试的代码: <!doctype html> <html lang="en"> ...

  8. input上传图片并预览

    首先说一下input 大家都知道上传文件,图片是通过input 的file进行上传的. 1. 首先是样式 大家都知道input在HTML的代码为 <input type="file&q ...

  9. vue中原生file上传图片

    效果 视图层 <el-form-item class="file-box" label="微信分享图片url链接" prop="wx_share ...

随机推荐

  1. 解决Plugin is too old,please update to a more recent version,or set ANDROID_DAILY_OVERRIDE..

    今天遇到了很诡异的事情. 昨天晚上还好好的工程今天就挂了,提示如下错误: Plugin is too old,please update to a more recent version,or set ...

  2. 【公开课】【阿里在线技术峰会】魏鹏:基于Java容器的多应用部署技术实践

    对于公开课,可能目前用不上这些,但是往往能在以后想解决方案的时候帮助到我.以下是阿里对公开课的整理 摘要: 在首届阿里巴巴在线峰会上,阿里巴巴中间件技术部专家魏鹏为大家带来了题为<基于Java容 ...

  3. Android下用Activity实现圆角的自定义弹窗

    这里我们使用9patch制作一个背景,找到SDK目录下的tools目录,双击draw9patch.bat文件,如下图: 打开想要编辑的文件,进行编辑(9patch的编辑教程自寻). 编辑完成后,保存到 ...

  4. Matlab以MEX方式调用C源代码

    #include "mex.h" // 使用MEX文件必须包含的头文件 // 执行具体工作的C函数 double add(double x, double y) { return ...

  5. LeetCode之“数组”:Rotate Array

    题目链接 题目要求: Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, ...

  6. RHEL6非交互式工具sshpass和expect安装

    RHEL6非交互式工具sshpass和expect安装 1 sshpass 在rhel6.4上,没有sshpass的软件包,无法采用yum方式安装.从源码编译安装非常简单. 1) 下载sshpass源 ...

  7. Apriori和FPTree

    Apriori算法和FPTree算法都是数据挖掘中的关联规则挖掘算法,处理的都是最简单的单层单维布尔关联规则. Apriori算法 Apriori算法是一种最有影响的挖掘布尔关联规则频繁项集的算法.是 ...

  8. 安卓TV开发(六) 移动智能终端UI之实现类似GridView的焦点控制FocusView框架

    转载请标明出处:http://blog.csdn.net/sk719887916/article/details/40045089,作者:skay 前言 安卓TV开发(五) 移动智能终端UI之实现主流 ...

  9. 坚持自己的追求,迎来 “中国系统开发网” (CSDN)的专访

    坚持自己的追求,迎来 "中国系统开发网" (CSDN)的专访: 专访马根峰:海量数据处理与分析大师的中国本土程序员" http://www.csdn.net/articl ...

  10. linux系统安装mysql数据库

    1.首先关闭linux的防火墙,执行命令 chkconfig iptables off 2.从mysql官网上下载自己适合的mysql版本https://dev.mysql.com/downloads ...