以前也实现过上传,只不过每次都是,写完之后没有总结,下次遇到时,还要重新写,重新调式,很是浪费时间,所以,今天实现一个上传图片的功能,包括简单的页面和servlet,下次再要写这个功能时,直接拿过来就可以了,没有理论,直接上代码+少量的注释。在最下面我会把项目上传,大家需要jar包,可以从项目中拿。
该项目用到的jar包如图,在下面的项目demo中有jar包:
一、upload.jsp页面代码:
[html] view plain copy
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <meta http-equiv="pragma" content="no-cache" />
- <base target="_self">
- <title>文件上传</title>
- </head>
- <body>
- <h5>文件上传</h5><hr/>
- <form id="file_upload_id" name="file_upload_name" action="upload" method="post" enctype="multipart/form-data">
- 文件名称:<input type="text" name="fileName" value="aaa.jpg"/>
- 作 者: <input type="text" name="author" value="jack"/>
- <div><input type="file" name="file_upload"/></div>
- <div><input type="submit" value="上传" /></div>
- </form>
- </body>
- </html>
二、web.xml配置文件代码:
[html] view plain copy
- <?xml version="1.0" encoding="UTF-8"?>
- <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">
- <display-name>UploadDemo</display-name>
- <welcome-file-list>
- <welcome-file>index.html</welcome-file>
- <welcome-file>index.htm</welcome-file>
- <welcome-file>index.jsp</welcome-file>
- <welcome-file>default.html</welcome-file>
- <welcome-file>default.htm</welcome-file>
- <welcome-file>default.jsp</welcome-file>
- </welcome-file-list>
- <servlet>
- <servlet-name>uploadPhoto</servlet-name>
- <servlet-class>com.upload.demo.UploadServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>uploadPhoto</servlet-name>
- <url-pattern>/upload</url-pattern>
- </servlet-mapping>
- </web-app>
三、UploadServlet代码:
[html] view plain copy
- package com.upload.demo;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.Properties;
- import java.util.UUID;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.fileupload.FileItem;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
- import com.lidroid.xutils.http.RequestParams;
- public class UploadServlet extends HttpServlet{
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- doPost(req, resp);
- };
- @Override
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- //服务器端接收,请求被后台拦截到这里
- exeUploadedInfos(request, response);
- };
- /**
- * 定义接口
- */
- public interface UploadStatusListener {
- public void status(boolean status, Map<String, String> params,
- List<String> files, HttpServletRequest request);
- }
- UploadStatusListener mUploadStatusListener = null;
- // 注册监听器,如果这里没有使用Vector而是使用ArrayList那么要注意同步问题
- public void addStatusListener(UploadStatusListener listener) {
- mUploadStatusListener = listener;
- }
- /**
- * @function:回调方法,执行图片上传,根据成功或失败的状态完成其他的操作
- * @param request
- * @param response
- */
- private void exeUploadedInfos(HttpServletRequest request,
- HttpServletResponse response) {
- UploadServlet up = new UploadServlet();
- up.addStatusListener(new UploadStatusListener() {
- public void status(boolean status, Map<String, String> params,
- List<String> files, HttpServletRequest request) {
- if (status) {//成功
- //Map中取值
- String memberId = params.get("memberId");
- //List中取值
- String fileUrl = files.get(0);
- System.out.println("===================================成功");
- } else {
- //失败
- System.out.println("========================================失败");
- }
- }
- });
- up.upload(request, response);
- }
- /**
- * @function:具体上传图片的功能在这里完成,
- * 然后调用接口回调方法mUploadStatusListener.status(flag, params, filenames , request);跳转到回调函数中
- * @param request
- * @param response
- */
- public void upload(HttpServletRequest request, HttpServletResponse response) {
- boolean flag = false;
- Map<String, String> params = new HashMap<String, String>();
- List<String> filenames = new ArrayList<String>();
- try {
- System.out.println("开始文件上传****************");
- request.setCharacterEncoding("utf-8"); // 设置编码
- // 设置上传文件最大为 3M
- final long MAX_SIZE = 3 * 1024 * 1024;
- // 1.创建一个解析器工厂
- DiskFileItemFactory factory = new DiskFileItemFactory();
- // 获取临时文件路径
- String savePath = "F:/upload/" ;//具体的路径
- if(!new File(savePath).exists()){
- new File(savePath).mkdirs();
- }
- factory.setRepository(new File(savePath));
- factory.setSizeThreshold(4096);
- // 2.得到一个解析器
- ServletFileUpload upload = new ServletFileUpload(factory);
- upload.setSizeMax(MAX_SIZE);
- // upload.setHeaderEncoding("UTF-8");
- // 3.将请求传入解析器,对请求进行解析
- List<FileItem> list = upload.parseRequest(request);
- // 4.迭代list集合,得到每个输入项的数据
- int count = 0 ;
- for (FileItem item : list) {
- count ++ ;
- // 5.判断item的类型
- if (item.isFormField()) {
- // 普通文本输入项
- String inputName = item.getFieldName();
- String inputValue = item.getString();
- params.put(inputName, inputValue);
- System.out.println("==================传进来的参数: "+count+"、"+inputName + "=" + inputValue);
- } else {
- // 上传文件输入项(如图片)
- String fileName = item.getName();// 获取文件名
- if (!"".equals(fileName)) {
- fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
- System.out.println("*************存放传过来的图片****************");
- InputStream in = item.getInputStream();
- FileOutputStream out = new FileOutputStream(savePath+fileName);
- byte[] buf = new byte[1024];
- int len = 0;
- while ((len = in.read(buf)) > 0) {
- out.write(buf, 0, len);
- }
- in.close();
- out.close();
- item.delete();// 删除临时文件
- filenames.add("上传成功了") ;
- flag = true;
- if (mUploadStatusListener != null) {
- System.out.println("======文件上传: ===flag=" + flag +";==="+ params.toString()
- + "==文件名fileName:=" + fileName);
- mUploadStatusListener.status(flag, params, filenames , request);
- }
- System.out.println("文件上传结束****************");
- }
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- request.setAttribute("message", "上传失败");
- System.out.println("***********上传失败******************");
- if (mUploadStatusListener != null) {
- System.out.println("****************上传失败*******************************");
- mUploadStatusListener.status(flag, params, filenames , request);
- }
- }
- }
- }
四、代码解释:
1、访问路径:http://localhost:8080/UploadDemo/upload.jsp
如图:
2、点击上传后,进入UploadServlet类
List<FileItem> list = upload.parseRequest(request);
产生临时上传文件
如图:
3、FileOutputStream out = new FileOutputStream(savePath+fileName);
创建要生成的图片
如图:
4、out.close();
执行完这行代码,上传图片的字节流写入完毕,完整图片如图
5、item.delete();// 删除临时文件,删除后如图:
五、项目下载: