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
    评论
Jsp+Servlet的文件上传 index.jsp <%@ page contentType="text/html; charset=GBK"%> <html> <head> <body> <form method="post" action="upload.jsp" name="pw" enctype="multipart/form-data"> 文件一 <input type="file" name="file1"> <br> 文件二 <input type="file" name="file2"> <br> 文件三 <input type="file" name="file3"> <br> <input TYPE="submit" value="确定上传"> </form> </body> </html> upload.jsp <%@ page language="java" import="fileUpload.*"%> <%@ page contentType="text/html;charset=gb2312"%> <%@ page errorPage="error.jsp"%> <%@ page import="java.io.File,java.util.*,java.text.*"%> <!-- 初始化一个upBean--> <jsp:useBean id="myUpload" scope="page" class="fileUpload.upBean" /> <% //初始化工作 myUpload.initialize(pageContext); //设定允许的文件后缀名 //myUpload.setAllowedExtList("gif,jpg"); //设定允许上传的文件类型 //gif:gif //jpg:pjpeg //text:plain //html:html //doc:msword // myUpload.setAllowedFileTypeList("gif,jpg"); //设定是否允许覆盖服务器上的同名文件 myUpload.setIsCover(false); //设定允许上传文件的总大小 //myUpload.setTotalMaxFileSize(1000000); //设定单个文件大小的限制 //myUpload.setMaxFileSize(100000); String myName = new String(""); //设定上传的物理路径 myUpload.setRealPath(application.getRealPath(File.separator + "upload")); try { //将所有数据导入组件的数据结构中 myUpload.upload(); } catch (Exception e) { throw e; } //得到所有上传的文件 files myFiles = myUpload.getFiles(); String[] sourceName = new String[myFiles.getCount()]; //文件的原始文件名数组 //将文件保存到服务器 try { for (int i = 0; i < myFiles.getCount(); i++) { Date date = new Date(); DateFormat df = new SimpleDateFormat("yyyyMMddHHmmsszzz"); String name = System.currentTimeMillis() + ""; // myName="myName"; // myName=myName+"_"+i+"."+myFiles.getFile(i).getExtName(); myName = name + "." + myFiles.getFile(i).getExtName(); //保存的图片名称 sourceName[i] = myFiles.getFile(i).getName(); myFiles.getFile(i).setName(myName); //有两种保存方法,一种是保存在myUpload.setRealPath()的设定路径中,使用saveAs(),一种是另外保存到其他文件夹,使用.saveAs(String realPath) myFiles.getFile(i).saveAs(); Thread.sleep(50); } } catch (Exception e) { throw e; } %> <html> <head> <title>上传结果</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <meta http-equiv="expires" content="fri,30 dec 1999 00:00:00 gmt"> <meta name="author" content="fredwebs@sina.com"> <link rel='stylesheet' href='style.css' type='text/css'> </head> <body bgcolor="#999999" style="margin: 0;"> 上传成功! </table> </body> </html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值