(jsp和Servlet 功能篇) Servlet 实现文件上传

你猜 阅读:671 2021-04-01 10:25:42 评论:0

在开发过程中用得比较多的上传组件是commons-fileupload和japSmartUpload,这两个组件都可以很好的完成文件上传的功能!

此例用commons-fileupload.这个组件在http://jakarta.apache.org/右边的搜索里面就能找到,顺带下载commons-io,commons-fileupload组件需要它的支持!将这两个组件的jar包放到项目的WEB-INF/lib文件夹,此时commons-fileupload组件的配置就算完成了!下面贴上源码....

 

上传文件(servlet)代码:

 

package com.rf.upload; 
 
import java.io.File; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.Iterator; 
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.FileItemFactory; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
 
public class UploadServlet extends HttpServlet { 
 
	/** 
	 *  
	 */ 
	private static final long serialVersionUID = 1L; 
 
	@Override 
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException { 
		// TODO Auto-generated method stub 
		// 判断提交过来的表单是否为文件上传菜单 
		boolean isMultipart = ServletFileUpload.isMultipartContent(request); 
		// 上传文件 
		if (isMultipart) { 
			// 构造一个文件上传处理对象 
			FileItemFactory factory = new DiskFileItemFactory(); 
			ServletFileUpload upload = new ServletFileUpload(factory); 
			// 迭代类 
			Iterator items; 
			try { 
				// 解析表单中提交的所有文件内容 
				items = upload.parseRequest(request).iterator(); 
				while (items.hasNext()) { 
					FileItem item = (FileItem) items.next(); 
					// 取出上传文件的文件名称 
					String name = item.getName(); 
					// 取得上传文件以后的存储路径 
					String fileName = name.substring( 
							name.lastIndexOf('\\') + 1, name.length()); 
					// 上传文件以后的存储路径(Tomact项目部署创建file文件) 
					String path = request.getRealPath("file") 
							+ File.separatorChar + fileName; 
					// 上传文件 
					File uploaderFile = new File(path); 
					item.write(uploaderFile); 
					// 打印上传成功信息 
					response.setContentType("text/html"); 
					response.setCharacterEncoding("GB2312"); 
					PrintWriter out = response.getWriter(); 
					out.print("<font size='2'>上传文件为:" + name + "<br>保存的地址为" 
							+ path + "</font>"); 
				} 
 
			} catch (Exception e) { 
				e.printStackTrace(); 
			} 
 
		} 
 
	} 
 
	@Override 
	public void doPost(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException { 
		// TODO Auto-generated method stub 
		doGet(req, resp); 
	} 
 
}


页面代码(jsp):

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
	<head> 
		<base href="<%=basePath%>"> 
 
		<title>My JSP 'index.jsp' starting page</title> 
		<meta http-equiv="pragma" content="no-cache"> 
		<meta http-equiv="cache-control" content="no-cache"> 
		<meta http-equiv="expires" content="0"> 
		<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> 
		<!-- enctype 默认是 application/x-www-form-urlencoded --> 
		<form action="FileUpload" enctype="multipart/form-data" method="post"> 
			上传文件: 
			<input type="file" name="file1"> 
			<br /> 
			<input type="submit" value="提交" /> 
		</form> 
	</body> 
</html>


结果截图:

标签:Servlet
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号