日期:2014-05-16 浏览次数:20497 次
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <html> <body> <!-- encType 必不可少 --> <form action="upImgServlet" method="post" encType=multipart/form-data> 描述: <input type="text" name="description"/><br/>选择图片: <input type="file" name="img"/> <input type="submit" value="提交"/> </form> </body> </html>
public class UpImgServlet extends HttpServlet { public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); // org.apache.commons.fileupload.DiskFileUpload 是一个开源包里的。 DiskFileUpload du = new DiskFileUpload(); du.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB du.setSizeThreshold(4096);// 设置缓存区大小 ,4 kb; // up 为 /WebRoot 下的 一个目录 du.setRepositoryPath(request.getSession().getServletContext() .getRealPath("/up"));// 设置缓存目录 // 得到所有文件 try { List list = du.parseRequest(request); Iterator it = list.iterator(); while (it.hasNext()) { org.apache.commons.fileupload.FileItem fileItem = (FileItem) it .next(); // 是否为表单元素。如文本框 等等。 if (fileItem.isFormField()) { String name = fileItem.getFieldName(); //通过流 用来读取表单元素里的内容。 java.io.BufferedReader br = new BufferedReader( new InputStreamReader(fileItem.getInputStream())); //如果还有除文件域以外的其他表单元素 就用 if()进行名字一一匹配。 if(name.equals("description")){ String contents = br.readLine(); System.out.println(contents); } } // 文件域 else { // 获得文件名,这个文件名包括路径: String fileName = fileItem.getName(); int index = fileName.lastIndexOf('.'); fileName = fileName.substring(index); fileName = this.getFileName() + fileName; //文件保存位置 fileItem.write(new File(request.getSession().getServletContext().getRealPath("/img")+ "\" + fileName)); System.out.println("上传成功"); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } PrintWriter out = response.getWriter(); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } public void init() throws ServletException { // Put your code here } // 以日期 获得一个文件名。(不重复); String getFileName() { java.util.Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int mon = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DATE); int hour = cal.get(Calendar.HOUR); int min = cal.get(Calendar.MINUTE); int sec = cal.get(Calendar.SECOND); int mi = cal