微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

十六、ajax上传图片 mvc

一、ajax上传图片 mvc

前台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">
                <div id="uploadimg" class="uploadPhoto" onclick="uploadPhoto()">
                    +
                </div>

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后台接收

   /// <summary>
        /// 上传图片
        /// </summary>
        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
            });
 
        }

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐