.net 跨域上传图片

发布日期:2020-01-16 15:44:01

前端


<!DOCTYPE html>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
  
    <input type="file" id="myphoto" />
    <div style="display:none" id="div_div1">
        <img src="#" id="img_myphoto" />
    </div>
</body>
</html>
<script src="/Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">



    $("#myphoto").change(function () {
        var file = this.files[0];
        var formData = new FormData();
        formData.append('tFile', file);
        jQuery.support.cors = true;
        $.ajax({
            type: "POST", // 必须用post
            url: "http://172.11.1.92:5678/Home/UploadRemote",
            crossDomain: true,
            data: formData,
            contentType: false,
            processData: false,
            success: function (data) {
                if (data.data == 1) {
                    $("#img_myphoto").attr("src", "http://172.11.1.92:5678" + data.url);
                    $("#div_div1").show();
                }
                else {
                    alert(data.msg);
                }
            },
            error: function (res) {
                alert('shit');
            }
        });
    });


</script>


后端


        public JsonResult UploadRemote()
        {
            Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (Request.HttpMethod == "OPTIONS")
            {
                Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
                Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept,X-Requested-With");
                Response.End();
            }


            var res = new JsonResult();


            HttpPostedFileBase imageName = Request.Files["tFile"];
            string file = imageName.FileName;
            string fileFormat = file.Split('.')[file.Split('.').Length - 1];
            string timeStamp = DateTime.Now.Ticks.ToString(); // 获取当前时间的string类型
            string firstFileName = timeStamp.Substring(0, timeStamp.Length - 4); // 通过截取获得文件名
            string imageStr = "UploadImages/"; // 获取保存图片的项目文件夹
            string uploadPath = Server.MapPath("~/" + imageStr); // 将项目路径与文件夹合并
            string pictureFormat = file.Split('.')[file.Split('.').Length - 1];// 设置文件格式
            string fileName = firstFileName + "." + fileFormat;// 设置完整(文件名+文件格式) 
            string saveFile = uploadPath + fileName;//文件路径
            imageName.SaveAs(saveFile);// 保存文件
            // 如果单单是上传,不用保存路径的话,下面这行代码就不需要写了!
            string image = "/" + imageStr + fileName;// 设置数据库保存的路径




            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            var result = new { data = 1, url = image };
            res.Data = result;
            return res;
        }