php上传图片参考!
 <button type="button" class="layui-btn" id="test1">
        <i class="layui-icon">&#xe67c;</i>选择图片    </button>
    <button type="button" class="layui-btn" id="btnUpload">开始上传</button>
    <img id="myPic" src="" width="500" />

JS代码

复制代码

  <script>
        layui.use(['upload', 'jquery'], function () {            var upload = layui.upload;            var $ = layui.$;            //执行实例
            var uploadInst = upload.render({
                elem: '#test1'                //绑定元素
                , url: '/Home/UploadImg'      //上传接口


                //*********************传输限制
                , size: 100                   //传输大小100k
                , exts: 'jpg|png|gif|'        //可传输文件的后缀
                , accept: 'file'              //video audio images


                //****************传输操作相关设置
                , data: { Parm1: "hello", Parm2: "world" }    //额外传输的参数
                , headers{token:'sasasasa'}                   //额外添加的请求头
                , auto: false                                 //自动上传,默认是打开的
                , bindAction: '#btnUpload'                    //auto为false时,点击触发上传
                , multiple: false                             //多文件上传
                //, number: 100                               //multiple:true时有效               
                , done: function (res) {                      //传输完成的回调                    console.log(res.IsSuccess)
                    console.log(res.Msg)
                    $('#myPic').attr("src", res.Src);
                }
                , error: function () {                         //传输失败的回调
                    //请求异常回调                }
            });
        });    </script>

复制代码

后台接口(使用.net mvc)

复制代码

       public ActionResult UploadImg(string Parm1,string Parm2)
        {            if (Request.Files.Count>0)
            {                //p1,p2没什么用,只是为了证明前端中额外参数data{parm1,parm2}成功传到后台了
                string p1 = Parm1;                string p2 = Parm2;                //获取后缀名
                string ext = Path.GetExtension(Request.Files[0].FileName);                //获取/upload/文件夹的物理路径
                string mapPath = Server.MapPath(Request.ApplicationPath);                //通过上传时间来创建文件夹,每天的放在一个文件夹中
                string dir = mapPath + "upload/"+DateTime.Now.ToString("yyyy-MM-dd");
                DirectoryInfo dirInfo = Directory.CreateDirectory(dir);                //在服务器存储文件,文件名为一个GUID
                string fullPath = dir + "/" + Guid.NewGuid().ToString()+ ext;
                Request.Files[0].SaveAs(fullPath);                //获取图片的相对路径
                string imgSrc = fullPath.Replace(mapPath, "/");                return Json(new { IsSuccess = 1, Msg = "上传成功", Src = imgSrc });
            }            else
            {                return Json(new { IsSuccess = 0, Msg = "上传失败", Src = "" });
            }
        }



写的好!

微信扫一扫赏大洋