使用commons-fileupload多文件上传例子

准备: commons-fileupload-1.2.1.jar和commons-io-1.4.jar


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//System.out.println(request.getParameter("test"));
request.setCharacterEncoding("utf-8");// 设置字符编码为UTF-8, 统一编码,处理出现乱码问题


//response.setContentType("text/html;charset=utf-8");
//response.setCharacterEncoding("utf-8");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);//检查是否是一个文件上传请求
if(isMultipart){
// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory factory = new DiskFileItemFactory();

// 设置上传文件时用于临时存放文件的内存大小,这里是2K.多于的部分将临时存在硬盘
factory.setSizeThreshold(1024*2);
// 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录
factory.setRepository(new File("c:\\file"));//临时文件

// 以上两项可通过DiskFileItemFactory构参来创建
// DiskFileItemFactory factory = new DiskFileItemFactory(yourMaxMemorySize, yourTempDirectory);


// 用上面的工厂实例化上传组件,
ServletFileUpload upload = new ServletFileUpload(factory);
//upload.setFileItemFactory(factory);
// 如果ServletFileUpload实例中不设置上面的Factory则报java.lang.NullPointerException: No FileItemFactory has been set.

// 设置最大上传大小 10M
upload.setSizeMax(1024*1024*10);
String name = "";
try {
List items = upload.parseRequest(request); // 得到所有FileItem
Iterator iter = items.iterator();
// 循环处理所有文件
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {// 判断是否是表单元素(<input type="text" />单选,多选等)
name = item.getName();// 得到文件的名称
if(name==null || "".equals(name.trim())){
// 未选择上传文件
continue;
}

long size = item.getSize();//文件长度
File file = new File("c:\\file\\"+name);
if(file.exists()){
file.delete();
}
item.write(file);
}else{
//<input name="test" size="40" type="text">
//String value = item.getString();//表单元素的值,用在非文件上传域中
//String fieldName = item.getFieldName();表单元素的名称,用在非文件上传域中 **test**
System.out.println(item.getFieldName()+" "+new String(item.getString().getBytes("ISO-8859-1"),"utf-8"));//处理中文问题
}
}

} catch (FileUploadException e) {
// 处理文件尺寸过大异常
e.printStackTrace();
} catch (Exception e) {
// 处理文件写入时的异常
System.out.println("Write Error: "+name);
e.printStackTrace();
}
}
request.getRequestDispatcher("/jsp/su.jsp").forward(request, response);
}


使用流读取:

//API中提供的按流的形式读取
void uploadByStream(HttpServletRequest request) throws FileUploadException, IOException{

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
String name = "";
if (isMultipart) {
ServletFileUpload upload = new ServletFileUpload();
upload.setSizeMax(1024*1024*10);
FileItemIterator fileItemIterator = upload.getItemIterator(request);
while(fileItemIterator.hasNext()){
FileItemStream stream = fileItemIterator.next();
if(!stream.isFormField()){
name = stream.getName();// 得到文件的名称
if(name==null || "".equals(name.trim())){
continue;
}
File file = new File("c:\\file\\"+name);
if(file.exists()){
file.delete();
}
InputStream is = stream.openStream();
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
long size = Streams.copy(is,bStream,true);
OutputStream op = new FileOutputStream(file);
bStream.writeTo(op);

}else{
InputStream is = stream.openStream();
InputStreamReader isr = new InputStreamReader(is,"utf-8");
BufferedReader br = new BufferedReader(isr);
char b[] = new char[1024];
int len = 0;
StringBuffer sb = new StringBuffer();
String line = null;
while((line=br.readLine())!=null){
sb.append(line);
}
// while((len=isr.read(b))!=-1){
// System.out.println("len= "+len);
// sb.append(new String(b,0,len));
// }
System.out.println(stream.getFieldName()+" "+sb.toString());
}
}
}
}

HTML:

<FORM action="/servlet/FileUpServlet" method="post" enctype="multipart/form-data">
<table border="1" width="450" cellpadding="4" cellspacing="2" bordercolor="#9BD7FF">

<tr><td width="100%" colspan="2">

文件1:<input name="x" size="40" type="file">

</td></tr>

<tr><td width="100%" colspan="2">

文件2:<input name="y" size="40" type="file">

</td></tr>

<tr><td width="100%" colspan="2">

文件3:<input name="z" size="40" type="file">

</td></tr>
<tr><td width="100%" colspan="2">

文件4:<input name="a" size="40" type="file">

</td></tr>
<tr><td width="100%" colspan="2">

文件5:<input name="b" size="40" type="file">

</td></tr>

<tr><td width="100%" colspan="2">

文件6:<input name="test" size="40" type="text">

</td></tr>

</table>

<br/><br/>

<table>

<tr><td align="center"><input name="upload" type="submit" value="开始上传"/></td></tr>

</table>


</FORM>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值