- 导包
向项目中的WEB-INF下的lib目录中导入下面两个包:commons-fileupload.jar包和commons-io.jar包 - 编写上传servlet代码。
public class UploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
File file = new File (this.getServletContext().getRealPath("/tempfile"));
if(!file.exists())
file.mkdirs();
DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024,file);
ServletFileUpload upload = new ServletFileUpload(factory);
if(ServletFileUpload.isMultipartContent(request)){
upload.setHeaderEncoding("UTF-8");
List<FileItem> items = upload.parseRequest(request);
for(FileItem item:items){
if(item.isFormField()){
String fieldname = item.getFieldName();
String content = item.getString("UTF-8");
}else{
String name = item.getName();
String filename = FileUploadUtils.getRealName(name);
String uuidname = FileUploadUtils.getUUIDFileName(filename);
String hashDirectory=FileUploadUtils.getHashDirectory(filename);
String parentPath =this.getServletContext().getRealPath("/upload");
File hd = new File(parentPath,hashDirectory);
if(!hd.exists)
hd.mkdirs();
IOUtils.copy(item.getInputStream(),new FileOutputStream(new File(hd,uuidname)));
item.delete();
}
}
}else{
response.getWrite().write("这不是上传请求");
return;
}
}
- 自定义上传工具类。
public class FileUploadUtils {
public static String getRealName(String filename){
int index = filename.lastIndexOf("\\")+1;
return filename.substring(index);
}
public static String getUUIDFileName(String filename){
int index = filename.indexOf(".");
if(index!=-1)
return UUID.randomUUID()+filename.substring(index);
else
return UUID.randomUUID().toString();
}
public static String getHashDirectory(String filename){
int hashcode = filename.hashCode();
int a = hashcode & 0xf;
hashcode = hashcode>>>4;
int b = hashcode & 0xf;
return "/"+a+"/"+b;
}
}