问题:使用fileupload如何跨域上传图片?
解决:跨域问题可以前端解决,也可以后端解决
方法:
方法一:配置fileupload
$('#fileupload').fileupload({
url: config.getUrl()+"upload!upload.do",
type:"POST",
dataType:"json",
autoUpload : true,
acceptFileTypes: /(\.|\/)(jpe?g|png)$/i,
formData: {model:1},
forceIframeTransport: true, # 实现跨域
redirectParamName:"callUrl",
redirect:"http://"+window.location.host+"/app/callupload.html?", // 回调页面,接受回调
done: function (e, data) {
$.each(data.result.files, function (index, file) {
model.fileVO.push({attach_root_id:file.id,file_path:file.url});
});
},
fail:function(e,data){
console.log("上传失败:"+data.errorThrown);
}
});
因此方法需要增加回调页面,不是我需要的,所以放弃。
方法二:配置后端nginx
因为访问的是使用nginx实现的上传功能,所以配置nginx访问限制
在nginx的location中添加
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
参考:
https://www.cnblogs.com/ZHF/p/5057416.html
https://www.cnblogs.com/cfas/p/9100827.html
https://segmentfault.com/a/1190000012550346?utm_source=tag-newest