图片上传功能<转>http://blog.csdn.net/u011159417/article/details/50126023

时间:2024-05-18 16:06:26

以前也实现过上传,只不过每次都是,写完之后没有总结,下次遇到时,还要重新写,重新调式,很是浪费时间,所以,今天实现一个上传图片的功能,包括简单的页面和servlet,下次再要写这个功能时,直接拿过来就可以了,没有理论,直接上代码+少量的注释。在最下面我会把项目上传,大家需要jar包,可以从项目中拿。

该项目用到的jar包如图,在下面的项目demo中有jar包:

图片上传功能<转>http://blog.****.net/u011159417/article/details/50126023

一、upload.jsp页面代码:

[html] view plain copy

print?

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <meta http-equiv="pragma" content="no-cache" />
  8. <base target="_self">
  9. <title>文件上传</title>
  10. </head>
  11. <body>
  12. <h5>文件上传</h5><hr/>
  13. <form id="file_upload_id" name="file_upload_name" action="upload" method="post" enctype="multipart/form-data">
  14. 文件名称:<input type="text" name="fileName" value="aaa.jpg"/>
  15. 作       者: <input type="text" name="author" value="jack"/>
  16. <div><input type="file" name="file_upload"/></div>
  17. <div><input type="submit" value="上传" /></div>
  18. </form>
  19. </body>
  20. </html>

二、web.xml配置文件代码:

[html] view plain copy

print?

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  3. <display-name>UploadDemo</display-name>
  4. <welcome-file-list>
  5. <welcome-file>index.html</welcome-file>
  6. <welcome-file>index.htm</welcome-file>
  7. <welcome-file>index.jsp</welcome-file>
  8. <welcome-file>default.html</welcome-file>
  9. <welcome-file>default.htm</welcome-file>
  10. <welcome-file>default.jsp</welcome-file>
  11. </welcome-file-list>
  12. <servlet>
  13. <servlet-name>uploadPhoto</servlet-name>
  14. <servlet-class>com.upload.demo.UploadServlet</servlet-class>
  15. </servlet>
  16. <servlet-mapping>
  17. <servlet-name>uploadPhoto</servlet-name>
  18. <url-pattern>/upload</url-pattern>
  19. </servlet-mapping>
  20. </web-app>

三、UploadServlet代码:

[html] view plain copy

print?

  1. package com.upload.demo;  
  2. import java.io.BufferedReader;  
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.InputStreamReader;  
  8. import java.util.ArrayList;  
  9. import java.util.Date;  
  10. import java.util.HashMap;  
  11. import java.util.List;  
  12. import java.util.Map;  
  13. import java.util.Properties;  
  14. import java.util.UUID;  
  15. import javax.servlet.ServletException;  
  16. import javax.servlet.http.HttpServlet;  
  17. import javax.servlet.http.HttpServletRequest;  
  18. import javax.servlet.http.HttpServletResponse;  
  19. import org.apache.commons.fileupload.FileItem;  
  20. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  21. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  22. import com.lidroid.xutils.http.RequestParams;  
  23. public class UploadServlet extends HttpServlet{  
  24. @Override  
  25. protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  26. throws ServletException, IOException {  
  27. doPost(req, resp);  
  28. };  
  29. @Override  
  30. protected void doPost(HttpServletRequest request,  
  31. HttpServletResponse response) throws ServletException, IOException {  
  32. //服务器端接收,请求被后台拦截到这里  
  33. exeUploadedInfos(request, response);  
  34. };  
  35. /**  
  36. *  定义接口  
  37. */  
  38. public interface UploadStatusListener {  
  39. public void status(boolean status, Map<String, String> params,  
  40. List<String> files, HttpServletRequest request);  
  41. }  
  42. UploadStatusListener mUploadStatusListener = null;  
  43. // 注册监听器,如果这里没有使用Vector而是使用ArrayList那么要注意同步问题  
  44. public void addStatusListener(UploadStatusListener listener) {  
  45. mUploadStatusListener = listener;  
  46. }  
  47. /**  
  48. * @function:回调方法,执行图片上传,根据成功或失败的状态完成其他的操作  
  49. * @param request  
  50. * @param response  
  51. */  
  52. private void exeUploadedInfos(HttpServletRequest request,  
  53. HttpServletResponse response) {  
  54. UploadServlet up = new UploadServlet();  
  55. up.addStatusListener(new UploadStatusListener() {  
  56. public void status(boolean status, Map<String, String> params,  
  57. List<String> files, HttpServletRequest request) {  
  58. if (status) {//成功  
  59. //Map中取值  
  60. String memberId = params.get("memberId");  
  61. //List中取值  
  62. String fileUrl = files.get(0);  
  63. System.out.println("===================================成功");  
  64. } else {  
  65. //失败  
  66. System.out.println("========================================失败");  
  67. }  
  68. }  
  69. });  
  70. up.upload(request, response);  
  71. }  
  72. /**  
  73. * @function:具体上传图片的功能在这里完成,  
  74. * 然后调用接口回调方法mUploadStatusListener.status(flag, params, filenames , request);跳转到回调函数中  
  75. * @param request  
  76. * @param response  
  77. */  
  78. public void upload(HttpServletRequest request, HttpServletResponse response) {  
  79. boolean flag = false;  
  80. Map<String, String> params = new HashMap<String, String>();  
  81. List<String> filenames = new ArrayList<String>();  
  82. try {  
  83. System.out.println("开始文件上传****************");  
  84. request.setCharacterEncoding("utf-8"); // 设置编码  
  85. // 设置上传文件最大为 3M  
  86. final long MAX_SIZE = 3 * 1024 * 1024;  
  87. // 1.创建一个解析器工厂  
  88. DiskFileItemFactory factory = new DiskFileItemFactory();  
  89. // 获取临时文件路径  
  90. String savePath = "F:/upload/" ;//具体的路径  
  91. if(!new File(savePath).exists()){  
  92. new File(savePath).mkdirs();  
  93. }  
  94. factory.setRepository(new File(savePath));  
  95. factory.setSizeThreshold(4096);  
  96. // 2.得到一个解析器  
  97. ServletFileUpload upload = new ServletFileUpload(factory);  
  98. upload.setSizeMax(MAX_SIZE);  
  99. // upload.setHeaderEncoding("UTF-8");  
  100. // 3.将请求传入解析器,对请求进行解析  
  101. List<FileItem> list = upload.parseRequest(request);  
  102. // 4.迭代list集合,得到每个输入项的数据  
  103. int count = 0 ;  
  104. for (FileItem item : list) {  
  105. count ++ ;  
  106. // 5.判断item的类型  
  107. if (item.isFormField()) {  
  108. // 普通文本输入项  
  109. String inputName = item.getFieldName();  
  110. String inputValue = item.getString();  
  111. params.put(inputName, inputValue);  
  112. System.out.println("==================传进来的参数:  "+count+"、"+inputName + "=" + inputValue);  
  113. } else {  
  114. // 上传文件输入项(如图片)  
  115. String fileName = item.getName();// 获取文件名  
  116. if (!"".equals(fileName)) {  
  117. fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);  
  118. System.out.println("*************存放传过来的图片****************");  
  119. InputStream in = item.getInputStream();  
  120. FileOutputStream out = new FileOutputStream(savePath+fileName);  
  121. byte[] buf = new byte[1024];  
  122. int len = 0;  
  123. while ((len = in.read(buf)) > 0) {  
  124. out.write(buf, 0, len);  
  125. }  
  126. in.close();  
  127. out.close();  
  128. item.delete();// 删除临时文件  
  129. filenames.add("上传成功了") ;  
  130. flag = true;  
  131. if (mUploadStatusListener != null) {  
  132. System.out.println("======文件上传:  ===flag=" + flag +";==="+ params.toString()  
  133. + "==文件名fileName:=" + fileName);  
  134. mUploadStatusListener.status(flag, params, filenames , request);  
  135. }  
  136. System.out.println("文件上传结束****************");  
  137. }  
  138. }  
  139. }  
  140. } catch (Exception e) {  
  141. e.printStackTrace();  
  142. request.setAttribute("message", "上传失败");  
  143. System.out.println("***********上传失败******************");  
  144. if (mUploadStatusListener != null) {  
  145. System.out.println("****************上传失败*******************************");  
  146. mUploadStatusListener.status(flag, params, filenames , request);  
  147. }  
  148. }  
  149. }  
  150. }

四、代码解释:

1、访问路径:http://localhost:8080/UploadDemo/upload.jsp

如图:

图片上传功能<转>http://blog.****.net/u011159417/article/details/50126023

2、点击上传后,进入UploadServlet类

List<FileItem> list = upload.parseRequest(request);
产生临时上传文件

如图:

图片上传功能<转>http://blog.****.net/u011159417/article/details/50126023

3、FileOutputStream out = new FileOutputStream(savePath+fileName);
创建要生成的图片

如图:

图片上传功能<转>http://blog.****.net/u011159417/article/details/50126023

4、out.close();
执行完这行代码,上传图片的字节流写入完毕,完整图片如图

图片上传功能<转>http://blog.****.net/u011159417/article/details/50126023

5、item.delete();// 删除临时文件,删除后如图:

图片上传功能<转>http://blog.****.net/u011159417/article/details/50126023

五、项目下载:

上传图片demo下载,点这里