简单的上传图片
1.在index.jsp文件中的body之间加
<form action="/Test/servlet/RegisterServlet" method="post" enctype="multipart/form-data"> <br> 头像:<input type="file" name="userHead"> <br> <input type="submit" value="提交"> </form>
2.在Test项目中创建servlet类命名为 RegisterServlet
在servlet文件中doPost方法中加
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); //保存路径 String Path= null; //判断请求消息中的内容是否是“multipart/form-data”类型 boolean multipart = ServletFileUpload.isMultipartContent(request); if (multipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> fileItems = upload.parseRequest(request); //将图片保存到指定文件夹下 File userHead = uploadHead(fileItems, "userHead"); if(userHead!=null && userHead.exists()) { String fullPath=userHead.getPath(); String[] paths=fullPath.split("/"); String fileName=paths[paths.length-1]; //拼出网络路径 Path= SystemConfig.API_BASE_URL_HEAD+fileName; } }catch (FileUploadException e) { e.printStackTrace(); } } //直接在网页中打印图片 // out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); // out.println("<HTML>"); // out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); // out.println(" <BODY>"); // out.println(" <img src=\""+Path+"\"> "); // out.println(" </BODY>"); // out.println("</HTML>"); // out.flush(); // out.close(); }
3.将图片保存到指定文件夹
把方法加到RegisterServlet类中
public File uploadHead(List<FileItem> items, String name) { for (FileItem item : items) { if (!item.isFormField() && name.equals(item.getFieldName())) { NameValuePair pair = FileHelper.getTempFile(item.getName()); File file = new File(pair.getKey()); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { item.write(file); } catch (Exception e) { e.printStackTrace(); } return file; } } return null; }
public class SystemConfig { public static final String API_BASE_URL_HEAD="http://127.0.0.1:8080/Test/img/";//图片的访问地址 public static final String API_BASE_PATH_HEAD="/Users/ty/Desktop/apache-tomcat-7.0.50/webapps/Test/img/";//要存储的路径 }
图片一定要放到tomcat下相应项目的文件夹下(不然会访问不到!)
5.FileHelper.java文件
public class FileHelper { public static NameValuePair getTempFile(String name) { //String path = System.currentTimeMillis() + "." + getEndWith(name); String path=getFileShortName(name); String key = SystemConfig.API_BASE_PATH_HEAD + path; return new NameValuePair(key, path); } public static String getEndWith(String fileName) { int i = fileName.lastIndexOf("."); if (i >= 0) { return fileName.substring(i + 1, fileName.length()); } return ""; } public static String getFileShortName(String fileName) { String[] strs=fileName.split("/"); return strs[strs.length-1]; } }6. NameValuePair.java文件
public class NameValuePair { private String key; private String value; public NameValuePair(String key, String value) { this.key = key; this.value = value; } public String getKey(){ return key; } public String getValue(){ return value; } public String toString(){ return "key="+key+";value="+value; } }