1.上传文件中的乱码
1.1解决文件的乱码
servletFileUpload.setHeaderEncoding("UTF-8")
1.2解决普通输入项的乱码(注意,表单类型为multipart/from-data的时候,设置request的编码是无效的)
2.在处理表单之前,要记得调用
servletFileUpload.isMultipartContent 方法判断提交表单的类型,如果该方法返回true ,则按上传方式处理,否则按照传统方式处理表单即可。
3.设置解析器缓冲区的大小,以及临时文件的删除
设置解析器缓冲区的大小 DiskFileItemFactory.setSizeThreshold(1024*1024);
临时文件的删除:在程序中处理完上传文件后,一定要记得调用item.delete()方法,以删除临时文件(要放在流关闭之后才能删除)
4.在做上传系统时候,千万要注意上传文件的保存目录,这个上传文件的保存目录绝对不能让外界直接访问到。
5.限制上传文件的类型
在处理上传文件时,判断上传文件的后缀名是不是允许的
6.限制上传文件的大小
调用解析器的ServletFileUpload.setFileSizeMax(1024*1024*5);就可以限制上传文件的大小,如果上次文件超出限制,则解析器会抛出FileUploadBase.FileSize
LimitExceededException异常,程序员通过是否抓到这个异常,进而就可以给用户友好提示。
7.如何判断空的上传输入项
String filename = item.getName().substring(item.getName().lastindexof("\\")+1);
if(filename == null || filename.trim().equals("")){
continue;//下面存入的细节不处理,进入下一个循环
}
8.为避免上次文件的覆盖,程序在保存上传文件时,要为每一个文件生成一个唯一的文件名。
public String generateFileName(String filename){
return UUID.randomUUID().toString()+"_"+filename;
}
q.为了避免在一个文件夹上面保存超过1000个文件,影响文件的访问性能,程序应该把上传文件打散后存储。
public String generateSavePath(String path,String filename){
int hashcode = filename.hashcode();
int dir1 = hashcode&15;
int dir2 = (hashcode>>4)%oxf;
String savepath = path *File.separator + dir1 +File.separator + dir2;
File file = new File(savepath);
if(!file.exists()){
file.mkdirs();
}
return savepath;
}
10.监听上传进度
servletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener(new ProgressListener(){
public void update(long pBytesRead, long pContentLenght, int Pitems){
System.out.println("当前已解析"+pBytesRead)
}
});
具体实现的相关代码:
public class WebUtils {
public static Upfile doUpload(HttpServletRequest request, String uppath) throws FileSizeLimitExceededException {
Upfile bean = new Upfile();
try{
DiskFileItemFactory factory = new DiskFileItemFactory();
//factory.setRepository(new File(request.getSession().getServletContext().getRealPath("/WEB-INF/temp")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
upload.setFileSizeMax(1000*1000*500);
List<FileItem> list = upload.parseRequest(request);
for(FileItem item : list){
if(item.isFormField()){
String name = item.getFieldName(); //username=aaa description=bbb
String value = item.getString("UTF-8");
BeanUtils.setProperty(bean, name, value);
}else{
//得到上传文件名
String filename = item.getName().substring(item.getName().lastIndexOf("\\")+1);
//得到文件的保存名称
String uuidname = generateFilename(filename);
//得到文件的保存路径
String savepath = generateSavePath(uppath,uuidname);
InputStream in = item.getInputStream();
int len = 0;
byte buffer[] = new byte[1024];
FileOutputStream out = new FileOutputStream(savepath + "\\" + uuidname);
while((len=in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
out.close();
item.delete();
bean.setFilename(filename);
bean.setId(UUID.randomUUID().toString());
bean.setSavepath(savepath);
bean.setUptime(new Date());
bean.setUuidname(uuidname);
}
}
return bean;
}catch (FileUploadBase.FileSizeLimitExceededException e) {
throw e;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String generateFilename(String filename){
String ext = filename.substring(filename.lastIndexOf(".")+1);
return UUID.randomUUID().toString()+ "." + ext;
}
private static String generateSavePath(String path,String filename){
int hashcode = filename.hashCode(); //121221
int dir1 = hashcode&15;
int dir2 = (hashcode>>4)&0xf;
String savepath = path + File.separator + dir1 + File.separator + dir2;
File file = new File(savepath);
if(!file.exists()){
file.mkdirs();
}
return savepath;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(!ServletFileUpload.isMultipartContent(request)){
request.setAttribute("message", "不支持的操作");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}
try{
String savepath = this.getServletContext().getRealPath("/WEB-INF/upload");
Upfile upfile =WebUtils.doUpload(request,savepath);
BusinessService service = new BusinessServiceImpl();
service.addUpfile(upfile);
request.setAttribute("message", "上传成功!!");
}catch (FileUploadBase.FileSizeLimitExceededException e) {
request.setAttribute("message", "文件不能超过500m");
}catch (Exception e) {
e.printStackTrace();
request.setAttribute("message", "上传失败");
}
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
BusinessService service = new BusinessServiceImpl();
Upfile upfile = service.findUpfile(id);
File file = new File(upfile.getSavepath() + "\\" + upfile.getUuidname());
if(!file.exists()){
request.setAttribute("message", "下载资源已被删除!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(upfile.getFilename(),"UTF-8"));
FileInputStream in = new FileInputStream(file);
int len = 0;
byte buffer[] = new byte[1024];
OutputStream out = response.getOutputStream();
while((len=in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
}