文件上传
首先写一个文件上传的页面
jsp页面:
<body> <form action="${ pageContext.request.contextPath }/UploadServlet" method="post" enctype="multipart/form-data"> <table border="1" width="600"> <tr> <td>文件描述</td> <td><input type="text" name="filedesc"></td> </tr> <tr> <td>文件上传</td> <td><input type="file" name="upload"></td> </tr> <tr> <td colspan="2"><input type="submit" value="上传"></td> </tr> </table> </form> </body>
在写servlet前解决文件重名问题
使用UUID作为随机的文件名
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") @MultipartConfig public 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); } }