Jsp页面实现文件上传下载类代码


刚才和lp看完电影,把jsp页面抽出class调整了一下。最近总上经典,是感觉既然当了斑竹,就该留下点什么。lp这几天也半开玩笑半生气的说,一回来就上经典,就发帖,你干脆娶经典作lp得了。想想,这几天是有点夸张,以后放慢速度了。保持1星期1帖吧,那样也能多想写,多总结些。
发帖的初衷就是有时候看到有的朋友问的问题,似乎还没有走进java的门,希望这样的帖子,能对新手一点帮助,也就满足了。有时候随意的一段话,其实也是自己的一点经验,而有时候之所以絮絮叨叨,是想把问题说的清楚明白,让高手见笑了。因为在入门的时候,每一个小环节都可能郁闷半天,如果看到我的某段话,有所帮助的话,即使我说十句有一句有帮助,我也满足了。因为我在不停的说话。

现在把总结的jsp页面上传类发布出来。代码肯定还会存在问题,有bug的话,告诉我,我及时修正。

名称:jsp页面上传类
作者:SinNeR
Mail:vogoals[at]hotmail.com

特点

  1. 可以多文件上传;
  2. 返回上传后的文件名;
  3. form表单中的其他参数也可以得到。

先贴上传类,JspFileUpload

package com.vogoal.util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
/*
* vogoalAPI 1.0
* Auther SinNeR@blueidea.com
* by vogoal.com
* mail: vogoals@hotmail.com
*/
/**
* JSP上传文件类
*
* @author SinNeR
* @version 1.0
*/
public class JspFileUpload {
/** request对象 */
private HttpServletRequest request = null;
/** 上传文件的路径 */
private String uploadPath = null;
/** 每次读取得字节的大小 */
private static int BUFSIZE = 1024 * 8;
/** 存储参数的Hashtable */
private Hashtable paramHt = new Hasptable();
/** 存储上传的文件的文件名的ArrayList */
private ArrayList updFileArr = new ArrayList();
/**
* 设定request对象。
*
* @param request
* HttpServletRequest request对象
*/
public void setRequest(HttpServletRequest request) {
this.request = request;
}
/**
* 设定文件上传路径。
*
* @param path
* 用户指定的文件的上传路径。
*/
public void setUploadPath(String path) {
this.uploadPath = path;
}
/**
* 文件上传处理主程序。�������B
*
* @return int 操作结果 0 文件操作成功;1 request对象不存在。 2 没有设定文件保存路径或者文件保存路径不正确;3
* 没有设定正确的enctype;4 文件操作异常。
*/
public int process() {
int status = 0;
// 文件上传前,对request对象,上传路径以及enctype进行check。
status = preCheck();
// 出错的时候返回错误代码。
if (status != 0)
return status;
try {
// ��参数或者文件名�u��
String name = null;
// 参数的value
String value = null;
// 读取的流是否为文件的标志位
boolean fileFlag = false;
// 要存储的文件。
File tmpFile = null;
// 上传的文件的名字
String fName = null;
FileOutputStream baos = null;
BufferedOutputStream bos = null;
// ��存储参数的Hashtable
paramHt = new Hashtable();
updFileArr = new ArrayList();
int rtnPos = 0;
byte[] buffs = new byte[BUFSIZE * 8];
// �取得ContentType
String contentType = request.getContentType();
int index = contentType.indexOf("boundary=");
String boundary = "--" + contentType.substring(index + 9);
String endBoundary = boundary + "--";
// �从request对象中取得流。
ServletInputStream sis = request.getInputStream();
// 读取1行
while ((rtnPos = sis.readLine(buffs, 0, buffs.length)) != -1) {
String strBuff = new String(buffs, 0, rtnPos);
// 读取1行数据�n��
if (strBuff.startsWith(boundary)) {
if (name != null && name.trim().length() > 0) {
if (fileFlag) {
bos.flush();
baos.close();
bos.close();
baos = null;
bos = null;
updFileArr.add(fName);
} else {
Object obj = paramHt.get(name);
ArrayList al = new ArrayList();
if (obj != null) {
al = (ArrayList) obj;
}
al.add(value);
System.out.println(value);
paramHt.put(name, al);
}
}
name = new String();
value = new String();
fileFlag = false;
fName = new String();
rtnPos = sis.readLine(buffs, 0, buffs.length);
if (rtnPos != -1) {
strBuff = new String(buffs, 0, rtnPos);
if (strBuff.toLowerCase().startsWith(
"content-disposition: form-data; ")) {
int nIndex = strBuff.toLowerCase().indexOf(
"name=\"");
int nLastIndex = strBuff.toLowerCase().indexOf(
"\"", nIndex + 6);
name = strBuff.substring(nIndex + 6, nLastIndex);
}
int fIndex = strBuff.toLowerCase().indexOf(
"filename=\"");
if (fIndex != -1) {
fileFlag = true;
int fLastIndex = strBuff.toLowerCase().indexOf(
"\"", fIndex + 10);
fName = strBuff.substring(fIndex + 10, fLastIndex);
fName = getFileName(fName);
if (fName == null || fName.trim().length() == 0) {
fileFlag = false;
sis.readLine(buffs, 0, buffs.length);
sis.readLine(buffs, 0, buffs.length);
sis.readLine(buffs, 0, buffs.length);
continue;
}else{
fName = getFileNameByTime(fName);
sis.readLine(buffs, 0, buffs.length);
sis.readLine(buffs, 0, buffs.length);
}
}
}
} else if (strBuff.startsWith(endBoundary)) {
if (name != null && name.trim().length() > 0) {
if (fileFlag) {
bos.flush();
baos.close();
bos.close();
baos = null;
bos = null;
updFileArr.add(fName);
} else {
Object obj = paramHt.get(name);
ArrayList al = new ArrayList();
if (obj != null) {
al = (ArrayList) obj;
}
al.add(value);
paramHt.put(name, al);
}
}
} else {
if (fileFlag) {
if (baos == null && bos == null) {
tmpFile = new File(uploadPath + fName);
baos = new FileOutputStream(tmpFile);
bos = new BufferedOutputStream(baos);
}
bos.write(buffs, 0, rtnPos);
baos.flush();
} else {
System.out.println("test :" + value + "--" + strBuff);
value = value + strBuff;
}
}
}
} catch (IOException e) {
status = 4;
}
return status;
}
private int preCheck() {
int errCode = 0;
if ( request == null )
return 1;
if ( uploadPath == null || uploadPath.trim().length() == 0 )
return 2;
else{
File tmpF = new File(uploadPath);
if (!tmpF.exists())
return 2;
}
String contentType = request.getContentType();
if ( contentType.indexOf("multipart/form-data") == -1 )
return 3;
return errCode;
}
public String getParameter(String name){
String value = "";
if ( name == null || name.trim().length() == 0 )
return value;
value = (paramHt.get(name) == null)?"":(String)((ArrayList)paramHt.get(name)).get(0);
return value;
}
public String[] getParameters(String name){
if ( name == null || name.trim().length() == 0 )
return null;
if ( paramHt.get(name) == null )
return null;
ArrayList al = (ArrayList)paramHt.get(name);
String[] strArr = new String[al.size()];
for ( int i=0;i<al.size();i++ )
strArr[i] = (String)al.get(i);
return strArr;
}

public int getUpdFileSize(){
return updFileArr.size();
}

public String[] getUpdFileNames(){
String[] strArr = new String[updFileArr.size()];
for ( int i=0;i<updFileArr.size();i++ )
strArr[i] = (String)updFileArr.get(i);
return strArr;
}
private String getFileName(String input){
int fIndex = input.lastIndexOf("\\");
if (fIndex == -1) {
fIndex = input.lastIndexOf("/");
if (fIndex == -1) {
return input;
}
}
input = input.substring(fIndex + 1);
return input;
}
private String getFileNameByTime(String input){
int index = input.indexOf(".");
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return input.substring(0,index) + sdf.format(dt) + input.substring(index);
}
}

说明

这个类基本解决了上一贴的上一贴说的存在的bug和不足。主要做了如下修正。

  1. 用户可以设定文件上传的路径,这里没有用request对象的getRealPath方法来取得相对路径,而是用了绝对路径。是一个小败笔。因为有时候用户只是得到服务器的一个应用,而不知道整个服务器的路径。但是既然getRealPath自己可以得到,用户自己取得也可以。
  2. 在文件上传处理的时候,预先进行了check,把一些可能出现的造成上传失败的情况拍查掉。避免该类出现不该出现的异常。
  3. 捕获了IO异常,避免文件上传的时候出现异常时程序的不友好表现
  4. 提供了方法返回form表单中其他参数的取得,模拟了HttpServletRequest对象的getParameter和getParameters方法(后面这个方法是叫这个名字么-_-b),取得Parameter的名称的方法没有提供,是个小缺陷。
  5. 提供了方法返回上传的文件的件数和上传的文件名,方便用户作其他操作。

现在介绍下JSP页面中如何用这个类实现上传。

首先,要把这个类编译后的class文件拷贝到WEB-INF/classes/目录下。注意保持package的结构。

在jsp页面中引用这个类

<%@page import="com.vogoal.util.JspFileUpload"%>

<%
//初始化
JspFileUpload jfu = new JspFileUpload();
//设定request对象
jfu.setRequest(request);
//设定上传的文件路径
jfu.setUploadPath("C:\\");
//上传处理
int rtn = jfu.process();
//取得form中其他input控件参数的值
String username = jfu.getParameter("username");
//如果对应同一个参数有多个input控件,返回数组
String[] usernameArr = jfu.getParameters("username");
//取得上传的文件的名字
String[] fileArr = jfu.getUpdFileNames();
//取得上传文件的个数,这个方法有点鸡肋
int fileNumber = jfu.getUpdFileSize();
//下面的是测试输出的代码。
// out.println("parameter:" + username);
// out.println("parameter size:" + usernameArr.length);
// out.println("fileArr size:" + fileArr.length);
// if (fileArr.length > 0)
// out.println("fileArr 0:" + fileArr[0]);
%>

使用的时候的注意事项

  1. 一定要设定request对象。
  2. 一定要设定正确的上传路径。
  3. 执行完了之后才可以得到其他参数,因为执行了之后这些参数才被分析。

1,2两点如果没有做到的话,process方法执行的时候汇报错。

各个用户可用的方法及说明

设定requet对象。
public void setRequest(HttpServletRequest request)

设定文件上传的路径。
public void setUploadPath(String path)

文件上传处理主程序。
@return int 操作结果 0 文件操作成功;1 request对象不存在。 2 没有设定文件保存路径或者文件保存路径不正确;3
没有设定正确的enctype;4 文件操作异常。
public int process()

根据name取得form表单中其他传递的参数的值(多个的话返回其中一个)
public String getParameter(String name)

根据name取得form表单中其他传递的参数的值(返回数组,可有多个)
public String[] getParameters(String name)

取得上传成功文件的个数
public int getUpdFileSize()

取得上传的文件名对应的数组。
public String[] getUpdFileNames()

注意process方法地返回值,在不是0的情况下操作失败。

以下提供测试类以及测试页面(见附件):

HelloPostFile.html
HelloPostFile.jsp
写在jsp中的代码的测试文件。
HelloPostFileWithClass.html
HelloPostFileWithClass.jsp
抽出class后的测试文件。
src在
WEB-INF/src/
class在
WEB-INF/classes/

另:
由于这个文件被我在中文日文系统下编辑过,注释出现乱码,所以大部分都删掉了,见谅。

下载:WEB-INF.zip


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3