java组件commons-fileupload文件上传示例
文件上传在web应用中非常普遍,要在java web环境中实现文件上传功能非常容易,因为网上已经有许多用java开发的组件用于文件上传,本文以使用最普遍的commons-fileupload组件为例,演示如何为java web应用添加文件上传功能。
commons-fileupload组件是apache的一个开源项目之一,可以从下载。该组件简单易用,可实现一次上传一个或多个文件,并可限制文件大小。
下载后解压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。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: java异步方式实现登录