欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ajax上传图片(mvc)代码教程

程序员文章站 2022-03-23 08:49:06
前台html

前台html

      <img id="uploadimg1" class="uploadimg" src="~/Content/img/sctp.png" width="60" height="60" />  
                <input type="file" id="inputimg" name="img_file" style="display:none">  
                <p id="uploadimg" class="uploadPhoto" onclick="uploadPhoto()">  
                    +  
                </p>  

js 上传成功返回url给img

 function uploadPhoto() {
        document.querySelector('#inputimg').value = null;
        $("#inputimg").click();
    }

    document.getElementById("inputimg").addEventListener("change", function (e) {
        var formData = new FormData();
        formData.append("file1", document.getElementById("inputimg").files[0]);
        $.ajax({
            url: "/PersonalCenter/UpLoadProcess",
            type: 'POST',
            data: formData,
            async: false,
            contentType: false,
            processData: false,
            success: function (msg) {
                if (msg.error == 0) {
                    $("#uploadimg1").attr("src", msg.message);
                    $("#uploadimg1").attr("data-imgurl", msg.message);
                }
            },
            error: function (msg) {
                alert(msg.error);
            }
        });
    })

c# mvc后台接收

   /// 
        /// 上传图片
        /// 
        public ActionResult UpLoadProcess(HttpPostedFileBase imgFile)
        {

            Hashtable hash = new Hashtable();
            if (Request.Files.Count <= 0)
            {
                hash = new Hashtable();
                hash["error"] = 1;
                hash["message"] = "请选择文件";
                return Json(hash);
            }
            imgFile = Request.Files[0];
            string fileTypes = "gif,jpg,jpeg,png,bmp";
            int maxSize = 10 * 1024 * 1024;
            string fileName = imgFile.FileName;
            string fileExt = Path.GetExtension(fileName).ToLower();
            if (imgFile.InputStream == null || imgFile.ContentLength > maxSize)  //file.InputStream.Length > maxSize ||
            {
                hash = new Hashtable();
                hash["error"] = 1;
                hash["message"] = "上传文件大小超过限制";
                return Json(hash);
            }

            if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                hash = new Hashtable();
                hash["error"] = 1;
                hash["message"] = "上传文件扩展名是不允许的扩展名";
                return Json(hash);
            }

            string filePathName = string.Empty;
            string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Resource");
            if (Request.Files.Count == 0)
            {
                return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = "id" });
            }
            string ex = Path.GetExtension(imgFile.FileName);
            filePathName = Guid.NewGuid().ToString("N") + ex;
            if (!System.IO.Directory.Exists(localPath))
            {
                System.IO.Directory.CreateDirectory(localPath);
            }
            imgFile.SaveAs(Path.Combine(localPath, filePathName));
            return Json(new
            {
                error = 0,
                message = "/Resource" + "/" + filePathName
            });

        }