现在的位置: 首页 > 综合 > 正文

使用Fileupload上传组件

2013年12月08日 ⁄ 综合 ⁄ 共 5098字 ⁄ 字号 评论关闭
 

使用Fileupload上传组件

   Java 项目中,当需要高性能上传文件时,往往就需要依靠组件,而不是手写的servlet了,一般的选择包括jakarta commons-fileupload以及smartupload,由于后者在上传大文件时往往会出错,另外对中文支持一般,笔者采用了前者。(这一点法老深有体会!)

   笔者写了一个名为Fileupload的类,用来封装上传动作。

   文件选择页面代码:   

<script language="JavaScript" type="text/JavaScript"> function check(){ if(document.Form1.checkbox[0].checked == true){ document.Form1.ch1.value = document.Form1.checkbox[0].value; } if(document.Form1.checkbox[1].checked == true){ document.Form1.ch2.value = document.Form1.checkbox[1].value; } var newAction = "11"; newAction = Form1.action + "?ch1=" + document.Form1.ch1.value + "&ch2=" + document.Form1.ch2.value; //更新action,使得后面通过页面url获取参数 Form1.action = newAction; } </script> <html> <head> <title>Excel文件上载</title></head> <body bgcolor="#FFFFFF" text="#000000"><p><font size="5"color="#FF0000"> <b>Excel文件上载</b></font></p> <p>文件上传 目的地选择</p> <form name="Form1" onSubmit="return check()" enctype="multipart/form-data" method="post" action="uploadResult.jsp"> <input type="checkbox" name="checkbox" value="ch1">公共文件夹 <input type="hidden" name="ch1" class="input" id="ch1" size="20"> <input type="checkbox" name="checkbox" value="ch2">测试文件夹 <input type="hidden" name="ch2" class="input" id="ch2" size="20"> <p>选择Excel文件 <input type="file" name="File1" size="20" maxlength="20"> </p> <p>注意:请确保选中的为Excel格式文件,Excel文件名不能包含空格,文件重名自动覆盖</p> <p> <input type="submit"value="提交"> <input type="reset" value="取消"> </p> </form>

 

 处理页面代码:

<% String temp = "C://TEMP"; char[] label = new char[2]; String labelString = ""; for(int i = 0; i < label.length; i++){ label[i] = '0'; } String des = request.getRealPath("/FinancialReports/excelFile"); //通过检测checkbox的选择情况,确定文件上传路径 //假设上传路径构成为serverPath + 2位标示符 + 具体文件名
if(request.getParameterValues("ch1") != null){ String[] ch1 = request.getParameterValues("ch1"); if(ch1[0].equals("ch1")){ System.out.println("ch1 checked..."); //添加文件标示 label[0] = '1'; } } if(request.getParameterValues("ch2") != null){ String[] ch2 = request.getParameterValues("ch2"); if(ch2[0].equals("ch2")){ System.out.println("ch2 checked..."); //添加文件标示 label[1] = '1'; } } for(int i = 0; i < label.length; i++){ labelString = labelString + label[i]; } des = des + "//" + labelString; System.out.println("Hello World: " + des); Fileupload fileUpload = new Fileupload(temp, des, request); boolean uploadResult = fileUpload.Upload(true); %>

 

 

Fileupload封装类:

/* * Author: Huang ye(www.hyweb.net) * 代码开源, 引用请注明出处 * * 2005-11-8 * */ package net.hyweb; import java.io.File; import java.util.*; import org.apache.commons.fileupload.*; import javax.servlet.http.HttpServletRequest; /** * @author Huangye * * TODO 要更改此生成的类型注释的模板,请转至 * 窗口 - 首选项 - Java - 代码样式 - 代码模板 */ public class Fileupload { //当上传文件超过限制时设定的临时文件位置 private String tempPath = "C://TEMP"; //文件上传目标目录 private String destinationPath; //获取的上传请求 private HttpServletRequest fileuploadRequest = null; //设置最多只允许在内存中存储的数据,单位:字节 private int sizeThreshold = 4096; //设置允许用户上传文件大小,单位:字节 //共10M private long sizeMax = 10485760; public Fileupload(){ } public Fileupload(String tempPath, String destinationPath){ this.tempPath = tempPath; this.destinationPath = destinationPath; } public Fileupload(String tempPath, String destinationPath, HttpServletRequest fileuploadRequest){ this.tempPath = tempPath; this.destinationPath = destinationPath; this.fileuploadRequest = fileuploadRequest; } /** 文件上载 * @return true —— success; false —— fail. */ public boolean Upload(){ //如果没有临时目录,则创建它 if(!(new File(tempPath).isDirectory())){ try{ new File(tempPath).mkdirs(); }catch(SecurityException e){ System.out.println("can not make security direcoty"); } } //如果没有上传目的目录,则创建它 if(!(new File(destinationPath).isDirectory())){ try{ new File(destinationPath).mkdirs(); }catch(SecurityException e){ System.out.println("can not make security direcoty"); } } //上传项目只要足够小,就应该保留在内存里。 //较大的项目应该被写在硬盘的临时文件上。 //非常大的上传请求应该避免。 //限制项目在内存中所占的空间,限制最大的上传请求,并且设定临时文件的位置。 DiskFileUpload fu = new DiskFileUpload(); //设置最多只允许在内存中存储的数据,单位:字节 fu.setSizeThreshold(sizeThreshold); //设置允许用户上传文件大小,单位:字节 //10M fu.setSizeMax(sizeMax); //设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录 fu.setRepositoryPath(tempPath); Iterator iter = null; //读取上传信息 try { List fileItems = fu.parseRequest(fileuploadRequest); //处理上传项目 //依次处理每个上传的文件 iter = fileItems.iterator(); } catch (FileUploadException e) { e.printStackTrace(); return false; } while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); //忽略其他不是文件域的所有表单信息 if (!item.isFormField()) { //上传的是文件信息 String fieldName = item.getFieldName(); String name = item.getName(); if((name == null) || name.equals("") && item.getSize() == 0){ continue; } System.out.println("processUploadedFile: " + name + " ; " + fieldName); String value = item.getString(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); String fileName = this.GetFileName(name); try { item.write(new File(this.destinationPath + fileName)); } catch (Exception e) { e.printStackTrace(); return false; } }else{ //上传的是普通表单字域 String fieldName = item.getFieldName(); String name = item.getName(); if((name == null) || name.equals("") && item.getSize() == 0){ continue; } String value = item.getString(); } } return true; } /**从路径中获取单独文件名 * @author Huangye * * TODO 要更改此生成的类型注释的模板,请转至 * 窗口 - 首选项 - Java - 代码样式 - 代码模板 */ public String GetFileName(String filepath) { String returnstr = "*.*"; int length = filepath.trim().length(); filepath = filepath.replace('//', '/'); if(length >0) { int i = filepath.lastIndexOf("/"); if (i >= 0) { filepath = filepath.substring(i + 1); returnstr = filepath; } } return returnstr; } /** * 省略所有的getXXX和setXXX访问器方法 */ }

抱歉!评论已关闭.