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。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
安卓(Android)动态创建多个按钮并添加监听事件
使用Java编写一个简单的Web的监控系统
![](https://img.aspxhome.com/file/2023/2/108222_0s.png)
android UI绘制加减号按钮
![](https://img.aspxhome.com/file/2023/1/128981_0s.jpg)
关于Android中WebView远程代码执行漏洞浅析
![](https://img.aspxhome.com/file/2023/7/126667_0s.jpg)
SpringBoot之@Value获取application.properties配置无效的解决
浅谈@FeignClient中name和value属性的区别
![](https://img.aspxhome.com/file/2023/0/78270_0s.png)
springboot做代理分发服务+代理鉴权的实现过程
![](https://img.aspxhome.com/file/2023/7/71597_0s.png)
深入理解Java抽象类
android Animation监听器AnimationListener的使用方法)
![](https://img.aspxhome.com/file/2023/4/94284_0s.jpg)
Java中的StringUtils引入及使用示例教程
java实战之飞机大战小游戏(源码加注释)
![](https://img.aspxhome.com/file/2023/5/63485_0s.png)
Java字节码ByteBuddy使用及原理解析上
![](https://img.aspxhome.com/file/2023/0/58290_0s.png)
C#模拟实现QQ窗体功能
![](https://img.aspxhome.com/file/2023/6/77236_0s.png)
详解Java执行groovy脚本的两种方式
![](https://img.aspxhome.com/file/2023/8/132018_0s.png)
SpringBoot整合BCrypt实现密码加密
![](https://img.aspxhome.com/file/2023/7/66067_0s.jpg)
Flutter的键值存储数据库使用示例详解
Android自定义ViewGroup实现绚丽的仿支付宝咻一咻雷达脉冲效果
![](https://img.aspxhome.com/file/2023/2/139102_0s.gif)
hibernate-validator改进校验框架validator v0.4使用
Maven生命周期和及插件原理用法详解
![](https://img.aspxhome.com/file/2023/2/75442_0s.png)
使用java.nio.file 库优雅的操作文件详解
![](https://img.aspxhome.com/file/2023/7/132077_0s.png)