最近工作中碰到上传文件插件使用问题:在工作中碰到app嵌套html5页面中使用上传文件问题,因为之前使用的是stream上传插件(http://www.twinkling.cn/),但是该插件跨域传输出现问题,无法传输成功,经过几次调试都无法解决跨域,然后我就换了个插件uploadify,一开始用的flash版本,但是此版本不支持在app中使用,于是就想到了用html5版本的,感觉笨死了,这个问题整了时间有点长了,下面开始说html版本的使用
首先,页面代码:
后台代码:
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 获得参数
String timestamp = request.getParameter("timestamp");
String token = request.getParameter("token");
System.out.println(timestamp);
System.out.println(token);
// 获得文件
String savePath = this.getServletConfig().getServletContext()
.getRealPath("");
savePath = savePath + "/uploads/";
File f1 = new File(savePath);
System.out.println(savePath);
if (!f1.exists()) {
f1.mkdirs();
}
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("utf-8");
List fileList = null;
try {
fileList = upload.parseRequest(request);
} catch (FileUploadException ex) {
System.out.println(ex.getMessage());
return;
}
Iterator<FileItem> it = fileList.iterator();
String name = "";
String extName = "";
while (it.hasNext()) {
FileItem item = it.next();
if (!item.isFormField()) {
name = item.getName();
long size = item.getSize();
String type = item.getContentType();
System.out.println(size + " " + type);
if (name == null || name.trim().equals("")) {
continue;
}
// 扩展名格式:
if (name.lastIndexOf(".") >= 0) {
extName = name.substring(name.lastIndexOf("."));
}
File file = null;
name = UUID.randomUUID().toString();
do {
// 生成文件名:
name = UUID.randomUUID().toString();
file = new File(savePath + name + extName);
} while (file.exists());
File saveFile = new File(savePath + name + extName);
try {
item.write(saveFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
response.getWriter().print(name + extName);
}
解决跨域问题主要是
第一:在web.xml中配置
<!-- 解决uploadify插件跨域 -->
<filter>
<filter-name>cors</filter-name>
<filter-class>cn.qtone.eduoa.web.filter.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 解决uploadify插件跨域 -->
第二:写过滤器SimpleCORSFilter
原文地址:https://www.cnblogs.com/yunshaowei/p/11968091.html