Java Servlet 文件上传

本文详述了如何在Servlet中利用commons-fileupload库进行文件上传的步骤,包括引入必要的JAR包,编写Servlet类,配置web.xml,以及创建index.jsp页面。尽管这种方法存在无法上传大文件的限制。
摘要由CSDN通过智能技术生成

平常项目中需要用到文件的上传,下面将详细介绍在Servlet中使用commons-fileupload-1.3.jar进行文件上传的经过。首先项目中要导入JAR包commons-fileupload-1.3.jar、commons-io-2.3.jar。但这也有缺点,不能上传大文件。

1、编写Servlet类

package com.fileupload;

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

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;

public class UpLoadServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		DiskFileItemFactory df = new DiskFileItemFactory();
		//设定阀值1M,如果超过这个值,则文件就直接写到临时文件,不会一直占用内存
		//利用这个特性可在上传大文件的时候不会占用大量内存,可以提高并发使用量。
		df.setSizeThreshold(1024 * 1024);
		
		try {
			File f = new File("E:\\preprocess_gd_package\\temp");
			if (!f.exists()) {
				f.mkdirs();
			}
			
			df.setRepository(f);
			ServletFileUpload sf = new ServletFileUpload(df);
			sf.setFileSizeMax(1024 * 1024 * 100);//上传文件最大为100M
			List list = sf.parseRequest(request);
			for (int i = 0; i < list.size(); i++) {
				FileItem fileItem = (FileItem) list.get(i);
				String fileName = fileItem.getName();
				if(fileName == null || "".equals(fileName.trim())){
					continue;
				}
				
				File ff = new File("E:\\preprocess_gd_package\\files");
				if (!ff.exists()) {
					ff.mkdirs();
				}
				
				File f2 = new File(ff, fileName);
				fileItem.write(f2);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		response.setContentType("text/html");
		response.setCharacterEncoding("GBK");
		PrintWriter out = response.getWriter();
		out.println("<script>alert('文件上传成功!');</script>");
		out.flush();
		out.close();
	}

}

 

2、配置web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

	<servlet>
		<servlet-name>Upload</servlet-name>
		<servlet-class>com.fileupload.UpLoadServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>Upload</servlet-name>
		<url-pattern>/fileupload</url-pattern>
	</servlet-mapping>

</web-app>


3、编写index.jsp文件

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
	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>文件上传</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">
	</head>

	<body>
		<form action="fileupload" method="post" enctype="multipart/form-data" name="form1">
			<input type="file" name="file">
			<input type="submit" name="Submit" value="upload">
		</form>

	</body>
</html>

4、运行结果


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值