`
hotfey
  • 浏览: 3142 次
最近访客 更多访客>>
社区版块
存档分类
最新评论
阅读更多
  • pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hotfey</groupId>
	<artifactId>ServletJspFileUpload</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>ServletJspFileUpload Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
	</dependencies>
	<build>
		<finalName>ServletJspFileUpload</finalName>
	</build>
</project>


  • web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
	<display-name>Archetype Created Web Application</display-name>
	<servlet>
		<servlet-name>FileUploadSverlet</servlet-name>
		<display-name>FileUploadSverlet</display-name>
		<description>FileUploadSverlet</description>
		<servlet-class>com.hotfey.sjfu.servlet.FileUploadSverlet</servlet-class>
		<init-param>
			<description>Define storage path for file uploads</description>
			<param-name>fileDirectroy</param-name>
			<param-value>/data/file/upload</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>FileUploadSverlet</servlet-name>
		<url-pattern>/FileUploadSverlet</url-pattern>
	</servlet-mapping>
</web-app>

  • index.jsp

<html>
<body>
<h2>Original multiple file upload</h2>
<form action="FileUploadSverlet" method="post" enctype="multipart/form-data">
	<input type="file" name="file1"><br>
	<input type="file" name="file2"><br>
	<input type="file" name="file3"><br>
	<input type="file" name="file4"><br>
	<input type="submit" value="submit">
</form>
<a href="fileupload/index.html">JQueryFileUploadDemo</a>
</body>
</html>

  • FileUploadSverlet.java

package com.hotfey.sjfu.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class FileUploadSverlet
 */
public class FileUploadSverlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private File fileUploadPath;
	private String realPath;
	private String fileDirectroy;

	@Override
	public void init() {
		realPath = this.getServletConfig().getServletContext().getRealPath("/");
		fileDirectroy = this.getServletConfig().getInitParameter(
				"fileDirectroy");
		fileUploadPath = new File(realPath + fileDirectroy);
		if (!fileUploadPath.exists()) {
			fileUploadPath.mkdirs();
		}
	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FileUploadSverlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String filePath = request.getParameter("filePath");
		if (filePath != null && !filePath.isEmpty()) {
			PrintWriter printWriter = response.getWriter();
			JSONArray files = new JSONArray();
			try {
				File removeFile = new File(fileUploadPath, filePath);
				if (removeFile.exists()) {
					boolean flag = removeFile.delete();
					JSONObject file = new JSONObject();
					if (flag) {
						file.accumulate("deleteWithCredentials", flag);
					}
					files.add(file);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				JSONObject result = new JSONObject();
				result.accumulate("files", files);
				printWriter.write(result.toString());
				if (printWriter != null) {
					printWriter.close();
				}
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Check that we have a file upload request
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// Configure a repository (to ensure a secure temp location is used)
			ServletContext servletContext = this.getServletConfig()
					.getServletContext();
			File repository = (File) servletContext
					.getAttribute("javax.servlet.context.tempdir");
			factory.setRepository(repository);

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			PrintWriter printWriter = response.getWriter();
			JSONArray files = new JSONArray();
			try {
				// Parse the request
				List<FileItem> items = upload.parseRequest(request);
				// Process the uploaded items
				Iterator<FileItem> iter = items.iterator();
				while (iter.hasNext()) {
					FileItem item = iter.next();
					if (item.isFormField()) {
						System.out.println(item.getFieldName());
					} else {
						String name = item.getName();
						if (!name.equals("")) {
							int index = name.indexOf("\\");
							File uploadedFile = null;
							if (index == -1) {
								uploadedFile = new File(fileUploadPath,
										File.separator + name);
							} else {
								name = name.substring(name
										.lastIndexOf(File.separator) + 1);
								uploadedFile = new File(fileUploadPath,
										File.separator + name);
							}
							item.write(uploadedFile);
							JSONObject file = new JSONObject();
							file.accumulate("name", name);
							file.accumulate("size", item.getSize());
							file.accumulate("url", ".." + fileDirectroy + "/"
									+ name);
							file.accumulate("deleteUrl",
									"../FileUploadSverlet?filePath=" + name);
							// It's better use POST, because IE will get from
							// cache first when use GET
							file.accumulate("deleteType", "post");
							files.add(file);
						}
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				JSONObject result = new JSONObject();
				result.accumulate("files", files);
				printWriter.write(result.toString());
				if (printWriter != null) {
					printWriter.close();
				}
			}
		} else {
			doGet(request, response);
		}
	}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics