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

在开发过程中用得比较多的上传组件是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>


结果截图:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值