前言
项目中使用webuploader进行文件上传,需要用到跨域,查看webuploader的issues发现是支持上传的,但是他们写的回复都是不清不白的,有点迷糊;想了半天才知道咋回事,也可能是我比较笨,再次记录下java中详细的处理。
webuploader进行上传,会执行2个请求;一个option请求,一个post(根据你的webuploader的配置method 值决定),需要在option请求中对响应头进行处理,post响应头也进行响应的处理。
以servlet为例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
@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);
}
|
再次测试跨域上传,正常
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。
原文链接:http://changeself.net/articles/webuploader-cros-java/