前言
项目中使用webuploader进行文件上传,需要用到跨域,查看webuploader的issues发现是支持上传的,但是他们写的回复都是不清不白的,有点迷糊;想了半天才知道咋回事,也可能是我比较笨,再次记录下java中详细的处理。
webuploader进行上传,会执行2个请求;一个option请求,一个post(根据你的webuploader的配置method 值决定),需要在option请求中对响应头进行处理,post响应头也进行响应的处理。
以servlet为例:
@webservlet(description = "文件上传",value = {"/file/upload"})
public class fileupload extends httpservlet {
public fileupload() {
super();
}
@override
protected void dopost(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {
resp.setheader("access-control-allow-origin", "*");
resp.setheader("access-control-allow-methods", "*");
resp.setheader("access-control-allow-headers", "x-requested-with,content-type");
resp.setcontenttype("application/json");
resp.setcharacterencoding("utf-8");
//文件上传逻辑
}
@override
protected void doget(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {
dopost(req, resp);
}
@override
protected void dooptions(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {
resp.setheader("access-control-allow-credentials", "false");
resp.setheader("access-control-allow-origin", "*");
resp.setheader("access-control-allow-methods", "*");
resp.setheader("access-control-allow-headers", "x-requested-with,content-type");
resp.setcontenttype("application/json");
resp.setcharacterencoding("utf-8");
super.dooptions(req, resp);
}
再次测试跨域上传,正常
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对萬仟网的支持。
希望与广大网友互动??
点此进行留言吧!