最近工作中碰到上传文件插件使用问题:在工作中碰到app嵌套html5页面中使用上传文件问题,因为之前使用的是stream上传插件(http://www.twinkling.cn/),但是该插件跨域传输出现问题,无法传输成功,经过几次调试都无法解决跨域,然后我就换了个插件uploadify,一开始用的flash版本,但是此版本不支持在app中使用,于是就想到了用html5版本的,感觉笨死了,这个问题整了时间有点长了,下面开始说html版本的使用
首先,页面代码:
后台代码:
@SuppressWarnings({ "unchecked", "rawtypes"})
protectedvoiddoGet(HttpServletRequestrequest,
HttpServletResponseresponse) throwsServletException, IOException{
// 获得参数
String timestamp = request.getParameter("timestamp");
String token = request.getParameter("token");
System.out.println(timestamp);
System.out.println(token);
// 获得文件
StringsavePath= this.getServletConfig().getServletContext()
.getRealPath("");
savePath= savePath+ "/uploads/";
File f1 = new File(savePath);
System.out.println(savePath);
if (!f1.exists()) {
f1.mkdirs();
}
DiskFileItemFactoryfac= newDiskFileItemFactory();
ServletFileUploadupload= newServletFileUpload(fac);
upload.setHeaderEncoding("utf-8");
List fileList = null;
try {
fileList = upload.parseRequest(request);
} catch(FileUploadExceptionex) {
System.out.println(ex.getMessage());
return;
}
Iterator it = fileList.iterator();
String name = "";
StringextName= "";
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());
FilesaveFile= newFile(savePath+ name+ extName);
try {
item.write(saveFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
response.getWriter().print(name + extName);
}
解决跨域问题主要是
第一:在web.xml中配置
cors
cn.qtone.eduoa.web.filter.SimpleCORSFilter
cors
/*
第二:写过滤器SimpleCORSFilter