一、文件上传(commons-fileupload-1.2.1.jar和commons-io-2.0.jar)
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1024*10); fileItemFactory.setRepository(new File("d:\\tmp")); ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory); servletFileUpload.setSizeMax(1024*1000); try { List<FileItem> lists = servletFileUpload.parseRequest(httpServletRequest); if(lists!=null){ for(FileItem fileItem : lists){ if(fileItem.isFormField()){ String fieldName = fileItem.getFieldName(); String fieldValue = fileItem.getString(); }else{ InputStream inputStream = fileItem.getInputStream(); String fileName = fileItem.getName(); byte[] b = new byte[1024]; int len=0; FileOutputStream fileOutputStream = new FileOutputStream("d:\\"+fileName); while((len=inputStream.read(b))!=-1){ fileOutputStream.write(b, 0, len); } fileOutputStream.close(); inputStream.close(); } } } } catch (FileUploadException e) { e.printStackTrace(); } }
文件下载
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.setContentType("application/x-msdownload"); String fileName = "爱情码头郑源.mp3"; httpServletResponse.setHeader("Content-Disposition", "p_w_upload;filename=" + URLEncoder.encode(fileName, "UTF-8")); OutputStream outputStream = response.getOutputStream(); InputStream inputStream = new FileInputStream("F:\\音乐\\" + fileName); byte[] b = new byte[1024]; int len = 0; while((len=inputStream.read(b))!=-1){ outputStream.write(b, 0, len); } inputStream.close(); }