java组件commons-fileupload文件上传示例
作者:廖雪峰 发布时间:2022-08-16 02:42:56
文件上传在Web应用中非常普遍,要在Java Web环境中实现文件上传功能非常容易,因为网上已经有许多用Java开发的组件用于文件上传,本文以使用最普遍的commons-fileupload组件为例,演示如何为Java Web应用添加文件上传功能。
commons-fileupload组件是Apache的一个开源项目之一,可以从http://commons.apache.org/fileupload/下载。该组件简单易用,可实现一次上传一个或多个文件,并可限制文件大小。
下载后解压zip包,将commons-fileupload-1.x.jar复制到tomcat的webapps/你的webapp/WEB-INF/lib/下,如果目录不存在请自建目录。
新建一个UploadServlet.java用于文件上传:
package com.liaoxuefeng.web;
public class FileUploadServlet extends HttpServlet {
private String uploadDir = "C:\\temp";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
// TODO:
}
}
当servlet收到浏览器发出的Post请求后,在doPost()方法中实现文件上传,我们需要遍历FileItemIterator,获得每一个FileItemStream:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
try {
ServletFileUpload upload = new ServletFileUpload();
// set max file size to 1 MB:
upload.setFileSizeMax(1024 * 1024);
FileItemIterator it = upload.getItemIterator(req);
// handle with each file:
while (it.hasNext()) {
FileItemStream item = it.next();
if (! item.isFormField()) {
// it is a file upload:
handleFileItem(item);
}
}
req.getRequestDispatcher("success.jsp").forward(req, resp);
}
catch(FileUploadException e) {
throw new ServletException("Cannot upload file.", e);
}
}
在handleFileItem()方法中读取上传文件的输入流,然后写入到uploadDir中,文件名通过UUID随机生成:
void handleFileItem(FileItemStream item) throws IOException {
System.out.println("upload file: " + item.getName());
File newUploadFile = new File(uploadDir + "/" + UUID.randomUUID().toString());
byte[] buffer = new byte[4096];
InputStream input = null;
OutputStream output = null;
try {
input = item.openStream();
output = new BufferedOutputStream(new FileOutputStream(newUploadFile));
for (;;) {
int n = input.read(buffer);
if (n==(-1))
break;
output.write(buffer, 0, n);
}
}
finally {
if (input!=null) {
try {
input.close();
}
catch (IOException e) {}
}
if (output!=null) {
try {
output.close();
}
catch (IOException e) {}
}
}
}
如果要在web.xml配置文件中读取指定的上传文件夹,可以在init()方法中初始化:
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
this.uploaddir = config.getInitParameter("dir");
}
最后在web.xml中配置Servlet:
<?xml version="1.0" encoding="UTF-8"?>
<!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>
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.liaoxuefeng.web.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
</web-app>
配置好Servlet后,启动Tomcat或Resin,写一个简单的index.htm测试:
<html>
<body>
<p>FileUploadServlet Demo</p>
<form name="form1" action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" name="button" value="Submit" />
</form>
</body>
</html>
注意action="upload"指定了处理上传文件的FileUploadServlet的映射URL。
当上传成功后,显示success.jsp,否则,抛出异常。如果上传的文件大小超过了我们设定的1MB,就会得到一个FileSizeLimitExceededException。
猜你喜欢
- 面试题1:你们是怎样保存用户密码等敏感数据的?本题回答参考朱晔的《Java业务开发常见错误100例》我们知道,用户名、密码、身份证等都属于用
- 先上效果图这个效果来自于三星S5的充电界面,当然有些细节差别,主要看思路.本文目的是技术交流,不要将效果直接运用于商业产品和项目.电池背景因
- 本文实例为大家分享了C# GDI+实现时钟表盘的具体代码,供大家参考,具体内容如下一、设计如下图界面按键“打开时钟&am
- 本文实例为大家分享了springboot实现异步任务的具体代码,供大家参考,具体内容如下1.什么异步任务同步:一定要等任务执行完了,得到结果
- 本文实例讲述了C#中累加器函数Aggregate用法。分享给大家供大家参考。具体如下:var shouldExclude = false;v
- 本文实例讲述了Java实现的两个线程同时运行。分享给大家供大家参考,具体如下:/** * 两个案例同时运行案例 * 1:这个两个线程并不是有
- java LRU(Least Recently Used )详解LRU是Least Recently Used 的缩写,翻译过来就是“最近最
- Java是一门面向对象的语言,即一切皆是对象!那么为何数据类型中还分为:基本类型和对象?Java中有8种基本数据类型boolean、byte
- 元注解是负责对其它注解进行说明的注解,自定义注解时可以使用元注解。Java 5 定义了 4 个注解,分别是 @Documented、@Tar
- 1、背景一般情况下,有些搜索需求是需要根据拼音和中文来搜索的,那么在elasticsearch中是如何来实现基于拼音来搜索的呢?可以通过el
- POM<dependency> <groupId>org.springframework.boot<
- 前言最近对 base-spring-boot 项目进行了升级。在将其用于应用开发中时遇到java.lang.ArrayStoreE
- 一、单例模式的思想想整理一些 java 并发相关的知识,不知道从哪开始,想起了单例模式中要考虑的线程安全,就从单例模式开始吧。以前写过单例模
- 这一篇网络爬虫的实现就要联系上大数据了。在前两篇java实现网络爬虫和heritrix实现网络爬虫的基础上,这一次是要完整的做一次数据的收集
- 最近要做一个java web项目,因为页面不是很多,所以就没有前后端分离,前后端写在一起,这时候就用到thymeleaf了,以下是不动脑式的
- 在Android开发中,我们不光可以使用已有的实现方式,而且,我们还可以利用Android这个智能手机平台,实现一些比较有特色的功能。本篇文
- 将jar包发布到Maven中央仓库(Maven Central Repository),这样所有的Java开发者都可以使用Maven直接导入
- 阻塞、无饥饿、无障碍、无锁、无等待几种。阻塞一个线程是阻塞的,那么在其他线程释放资源之前,当前线程无法继续执行。当我们使用synchroni
- 文件比较平常都是用Beyond Compare,可以说离不开的神器,特别是针对代码比较这块,确实挺好用的。不过Beyond Compare平
- class文件中的常量池之前我们在讲class文件的结构时,提到了每个class文件都有一个常量池,常量池中存了些什么东西呢?字符串常量,类