启用 CORS 来解决这个问题(ajax跨域请求)

时间:2023-03-10 01:45:47
启用 CORS 来解决这个问题(ajax跨域请求)
 <input type="file" name="btn_Upload" value="上传" id="btn_Upload" />
<img src="" alt="" id="img_Upload" /> @section Scripts
{
<link href="../../js/uploadifive-v1.2.2-standard/uploadifive.css" rel="stylesheet" />
<script src="../../js/uploadifive-v1.2.2-standard/jquery.uploadifive.js"></script>
} <script>
$(function () {
$('#btn_Upload').uploadifive({
formData: { openId: '@ViewBag.OpenId' },
multi: false,
uploadScript: '@WXCommon.ConfigHelper.UploadUrl',
onUploadComplete: function (file, data) {
if (data) {
var json = $.parseJSON(data);
if (json.res) {
alert(json.msg);
$('#img_Upload').attr({
src: '@WXCommon.ConfigHelper.ThumbnailPath' + '/' + '@ViewBag.OpenId' + '/' + json.fileName
});
} else {
alert(json.msg);
}
} else {
alert('服务器内部错误!');
}
}
});
});
</script>

Javascript

 //独立部署的图片服务器
public ActionResult Index()
{
//if (Request.HttpMethod == "OPTION")
//{
// Response.AddHeader("Access-Control-Allow-Methods", "GET,POST");
// Response.AddHeader("Access-Control-Allow-Headers", "Content-Type,Accept");
// Response.AddHeader("Access-Control-Max-Age", "1728000");
// Response.AddHeader("Access-Control-Allow-Origin", "*");
//}
string openId = Request["openId"];
HttpPostedFileBase httpPostedFileBase = Request.Files["Filedata"];
string fileName = httpPostedFileBase.FileName;
string extensionName = System.IO.Path.GetExtension(fileName).ToLower();
if (extensionName == ".jpg" || extensionName == ".jpeg")
{
string virtualPath = "/uploads" + "/" + fileName.Replace(extensionName, "") + DateTime.Now.ToString("yyyyMMddhhmmss") + extensionName;
string fullPath = Server.MapPath(virtualPath);
httpPostedFileBase.SaveAs(fullPath); string savePath = Server.MapPath("/thumbnails" + "/" + openId);
string thumbnailFileName = Thumbnail.GetThumbnailImage(, , fullPath, savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
//删除原始文件
//System.IO.File.Delete(fullPath);
NowModel model = new NowModel();
model.Id = ;
model.OpenId = openId;
model.FileName = thumbnailFileName;
nowBLL.Insert(model);
return Json(new { res = true, msg = "上传成功!", fileName = thumbnailFileName });
}
return Json(new { res = false, msg = "上传失败!" });
}

ASP.Net

   <!--仅试用于IIS7以上版本,IIS6.0请用Response.AddHeader的方式-->
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Methods" value="GET,POST,OPTION"/>
<add name="Access-Control-Allow-Headers" value="Content-Type,soapaction"/>
</customHeaders>
</httpProtocol>
</system.webServer>

图片服务器配置文件