fileupload上传文件java_使用FileUpload组件实现文件上传

文件上传在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:

/p>

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

UploadServlet

com.liaoxuefeng.web.FileUploadServlet

UploadServlet

/upload

配置好Servlet后,启动Tomcat或Resin,写一个简单的index.htm测试:

FileUploadServlet Demo

注意action="upload"指定了处理上传文件的FileUploadServlet的映射URL。

当上传成功后,显示success.jsp,否则,抛出异常。如果上传的文件大小超过了我们设定的1MB,就会得到一个FileSizeLimitExceededException。

下载完整的源代码:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
文件是Web开发中常见的功能之一,Java中也提供了多种方式来实现文件。其中,一种常用的方式是通过Apache的commons-fileupload组件实现文件。 以下是实现文件的步骤: 1.在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> ``` 2.在前端页面中添加文件表单: ```html <form method="post" enctype="multipart/form-data" action="upload"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> ``` 3.在后台Java代码中处理上文件: ```java // 创建一个DiskFileItemFactory对象,用于解析上文件 DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置缓冲区大小,如果上文件大于缓冲区大小,则先将文件保存到临时文件中,再进行处理 factory.setSizeThreshold(1024 * 1024); // 创建一个ServletFileUpload对象,用于解析上文件 ServletFileUpload upload = new ServletFileUpload(factory); // 设置上文件的大小限制,这里设置为10MB upload.setFileSizeMax(10 * 1024 * 1024); // 解析上文件,得到一个FileItem的List集合 List<FileItem> items = upload.parseRequest(request); // 遍历FileItem的List集合,处理上文件 for (FileItem item : items) { // 判断当前FileItem是否为上文件 if (!item.isFormField()) { // 获取上文件文件名 String fileName = item.getName(); // 创建一个File对象,用于保存上文件 File file = new File("D:/uploads/" + fileName); // 将上文件保存到指定的目录中 item.write(file); } } ``` 以上代码中,首先创建了一个DiskFileItemFactory对象,用于解析上文件。然后设置了缓冲区大小和上文件的大小限制。接着创建一个ServletFileUpload对象,用于解析上文件。最后遍历FileItem的List集合,判断当前FileItem是否为上文件,如果是,则获取文件名,创建一个File对象,将上文件保存到指定的目录中。 4.文件完成后,可以给用户一个提示信息,例如: ```java response.getWriter().write("File uploaded successfully!"); ``` 以上就是使用Apache的commons-fileupload组件实现文件的步骤。需要注意的是,文件可能会带来安全隐患,因此在处理上文件时,需要进行严格的校验和过滤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值