`

common-fileupload文件上传

阅读更多

req.setCharacterEncoding("utf-8");
Set<String> extSet = new HashSet<String>();
extSet.add("xls");
final long MAX_SIZE = 2*1024*1024;

DiskFileItemFactory dfif = new DiskFileItemFactory();
//设置临时文件的存储位置,文件夹
dfif.setRepository(new File(req.getRealPath("/")+"catch\\"));
ServletFileUpload sfu = new ServletFileUpload(dfif);
//限制上传文件大小
sfu.setSizeMax(MAX_SIZE);
List<FileItem> fileList = null;
//,解析请求正文,获取上传文件
try{
fileList = sfu.parseRequest(req);
}catch(FileUploadException e){
System.out.println("解析出错");
e.printStackTrace();
}
//对一个文件实体进行处理
FileItem fileItem = fileList.get(0);
String path = fileItem.getName();
String t_ext = path.substring(path.lastIndexOf(".")+1);
if(!extSet.contains(t_ext)){
req.setAttribute("info","只允许传.xls格式的文件");
req.getRequestDispatcher("index.jsp").forward(req, resp);
return;
}
long now = System.currentTimeMillis();
String prefix = String.valueOf(now);
//存储在本地的真实文件名
String u_name = req.getRealPath("/")+"file\\"+prefix+"."+t_ext;
//文件实体写入本地
try{
fileItem.write(new File(u_name));
}catch(Exception e){
e.printStackTrace();
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics