文件上传
首先写一个文件上传的页面
jsp页面:
public class UUIDUtils { public static String getUUID(){ return UUID.randomUUID().toString().replace("-", ""); } public static String getUUIDFileName(String fileName){ return UUID.randomUUID().toString().replace("-", "")+"_"+fileName; }}
解决一个目录下存放的文件过多的问题
public class UploadUtils { public static String getPath(String uuidFileName){ // 使用唯一文件名.hashCode(); int code1 = uuidFileName.hashCode(); int d1 = code1 & 0xf; // 获得到1级目录. int code2 = code1 >>> 4; int d2 = code2 & 0xf; // 获得到2级目录. return "/"+d1+"/"+d2; }}
此处的servlet是用的servlet3.0
/** * 文件上传的Servlet */@WebServlet("/UploadServlet")@MultipartConfigpublic class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 接收普通数据: request.setCharacterEncoding("UTF-8"); String filedesc = request.getParameter("filedesc"); System.out.println("文件描述"+filedesc); // 接收文件: Part part = request.getPart("upload"); long size = part.getSize();// 获得文件大小: System.out.println("文件大小:"+size); String name = part.getName(); System.out.println("文件表单中的name属性的名称"+name); // 获得文件名: String header = part.getHeader("Content-Disposition"); int idx = header.lastIndexOf("filename=\""); String fileName = header.substring(idx+10, header.length()-1); System.out.println("文件名:"+fileName); // 获得文件内容: InputStream is = part.getInputStream(); // 获得upload的路径: String path = this.getServletContext().getRealPath("/upload"); // 获得文件的唯一文件名: String uuidFileName = UUIDUtils.getUUIDFileName(fileName); String realPath = path+UploadUtils.getPath(uuidFileName); File file = new File(realPath); if(!file.exists()){ file.mkdirs(); } OutputStream os = new FileOutputStream(realPath+"/"+uuidFileName); byte[] b = new byte[1024]; int len = 0; while((len = is.read(b))!=-1){ os.write(b, 0, len); } is.close(); os.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}