【发布时间】:2019-05-28 06:46:14
【问题描述】:
我正在尝试使用 dropzone.js 向我的本地 Tomcat 服务器发送一个发布请求,但是,chrome 正在响应说明。
从源“http://localhost:7887”访问“https://testserver.local/upload”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。
悬停在上传时的 dropzonejs 状态
服务器以 0 代码响应。
但是在我的端点中,我有以下 doOptions 允许上述来源。
我是否在我的 CORS 选项中遗漏了某些内容,还是这是 dropzonejs 问题?
@WebServlet(value = "/upload", loadOnStartup = 0)
public class UploadEndpoint extends HttpServlet
{
private static final long serialVersionUID = 1L;
@Override
protected void doOptions(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
resp.setHeader("Access-Control-Allow-Origin", "http://localhost:7887");
resp.setHeader("Access-Control-Allow-Methods", "POST GET HEAD");
resp.setHeader("Access-Control-Allow-Headers", "*");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
if (!ServletFileUpload.isMultipartContent(request)) { throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form."); }
ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
PrintWriter writer = response.getWriter();
try
{
List<FileItem> items = uploadHandler.parseRequest(new ServletRequestContext(request));
for (FileItem item : items)
{
if (!item.isFormField())
{
File file = new File(request.getServletContext().getRealPath("/") + "uploads/", item.getName());
item.write(file);
}
}
}
catch (FileUploadException e)
{
throw new RuntimeException(e);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
finally
{
writer.close();
}
}
}
这是网页(为简单起见,已删除绒毛),当然您需要相关的 dropzonejs JavaScript 文件和 CSS 文件。
<html>
<head>
<script src="dropzone.js"></script>
<link rel="stylesheet" type="text/css" href="dropzone.css">
</head>
<body>
<form action="https://trainor.org.uk:19001/Music/upload" class="dropzone" id="drop_zone"></form>
</body>
</html>
【问题讨论】:
标签: javascript java tomcat cors dropzone