引言


   之前在做.net项目的时候经常会遇到文件上传和下载的需求,现在在java中同样有了这样的需求,其实做法


和.net差不多都是采用了第三方的东西来实现,今天就利用apache commons fileupload来实现文件的上传。


  jar包引入


   1、commons-fileupload-1.1.1.jar需要引入


   2、commons-io-1.2.jar需要引入


  html页面代码


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>index.html</title>

		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="this is my page">

		<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

	</head>

	<body>
		<form action="./servlet/item/FileUploadServlet" method="post"
			enctype="multipart/form-data" name="form1">
			<input type="file" name="file">
			<input type="submit" name="Submit" value="upload">
		</form>
		<form action="./servlet/HelloWord" method="post">
			<input type="submit" />
		</form>
		<form name="uploadform" method="POST" action="./servlet/item/FileUploadServlet"
			ENCTYPE="multipart/form-data">

			<table border="1" width="450" cellpadding="4" cellspacing="2"
				bordercolor="#9BD7FF">

				<tr>
					<td width="100%" colspan="2">

						文件1:
						<input name="x" size="40" type="file">

					</td>
				</tr>

				<tr>
					<td width="100%" colspan="2">

						文件2:
						<input name="y" size="40" type="file">

					</td>
				</tr>

				<tr>
					<td width="100%" colspan="2">

						文件3:
						<input name="z" size="40" type="file">

					</td>
				</tr>

			</table>

			<br />
			<br />

			<table>

				<tr>
					<td align="center">
						<input name="upload" type="submit" value="开始上传" />
					</td>
				</tr>

			</table>

		</form>

	</body>
</html>

   在html页面中我们需要注意的地方就是 form表单的头部的设置,提交方式必须为post提交,表单编码方式必须


为:enctype="multipart/form-data"。这样我们在servlet中才能接收道文件的相关信息完成上传。

  

  创建一个servlet实现逻辑


package com.bjpowernode.drp.basedata.web;

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

import javax.servlet.ServletException;
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;

public class FileUploadServlet extends HttpServlet {

	 private ItemManager itemManager; 
	// 用于存放上传文件的目录
	private File uploadPath;

	private File tempPath;

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		// form提交采用multipart/form-data,无法采用req.getParameter()取得数据
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(4096);
		// the location for saving data that is larger than getSizeThreshold()
		factory.setRepository(tempPath);

		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum size before a FileUploadException will be thrown
		upload.setSizeMax(1000000 * 20);
		try {
			List fileItems = upload.parseRequest(req);
			String itemNo = "";
			for (Iterator iter = fileItems.iterator(); iter.hasNext();) {
				FileItem item = (FileItem) iter.next();

				// 是普通的表单输入域
				if (item.isFormField()) {
					if ("itemNo".equals(item.getFieldName())) {
						itemNo = item.getString();
					}
				}
				// 是否为input="type"输入域
				if (!item.isFormField()) {
					String fileName = item.getName();
					long size = item.getSize();
					if ((fileName == null || fileName.equals("")) && size == 0) {
						continue;
					}
					// 截取字符串 如:C:\WINDOWS\Debug\PASSWD.LOG
					fileName = fileName.substring(
							fileName.lastIndexOf("\\") + 1, fileName.length());
					// item.write(new File(uploadPath + itemNo + ".gif"));
					item.write(new File(uploadPath, fileName));

					itemManager.uploadItemImage(itemNo, fileName);
				}
			}
			res.sendRedirect(req.getContextPath()
					+ "/servlet/item/SearchItemServlet");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void init() throws ServletException {
		uploadPath = new File(getServletContext().getRealPath("upload"));
		// 如果目录不存在
		if (!uploadPath.exists()) {
			// 创建目录
			uploadPath.mkdir();
		}

		// 临时目录
		tempPath = new File(getServletContext().getRealPath("temp"));
		if (!tempPath.exists()) {
			tempPath.mkdir();
		}

		 itemManager = new ItemManagerImpl();
	}
}

  我们将获取到的文件的名称(包括文件的后缀)存储在数据库中的一个字段中,这样我们在图片预览的时候会根


据数据库返回的名称来实现图片的显示。


  我们上传的文件存储在G:\myeclipseWorkSpace\apache-tomcat-7.0.63\webapps\drp2.0\upload,当然apache-


tomcat-7.0.63之前的路径根据项目存放的位置不同而改变。


   总结


   上面代码就可以粗略的完成了一个文件上传的功能了,当时实现方式有很多,这只是其中的一种,希望有别的


更好的实现的读者可以共享。


Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐