当前位置:主页 > 软件编程 > JAVA代码 >

java使用webuploader实现跨域上传详解

时间:2020-10-15 23:16:10 | 栏目:JAVA代码 | 点击:

前言

项目中使用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);
 }

再次测试跨域上传,正常

总结

您可能感兴趣的文章:

相关文章