您的位置:首页 > Web前端 > JavaScript

jsp文件上传而下载

2009-09-27 02:06 232 查看
由于时间比较晚了,就先简单的罗列一下吧
一、文件上传(upLoad.jsp)
<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<html>
<body>
<form action="up.jsp" method="post" enctype="multipart/form-data" >
<input type="hidden" name="test" value="good"/>
<table width="58%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="65%" height="30" align="right">
<input name="fileName_1" type="file" id="fileName_1"></td>
<td width="35%" height="30"> </td>
</tr>
<tr>
<td height="30" align="center">
<input type="submit" name="Submit" value="提交"></td>
<td height="30"> </td>
</tr>
</table>
</form>
<p><br>
文件下载</p>
<p><a href="downLoad.jsp?fileName=00.gif" id="00.gif" name="00.gif">00.gif</a></p>
<p>1.txt</p>
</body>
</html>
二、文件保存代码(up.jsp)
<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="java.io.*"%>
<html>
<head>
<title> upFile </title>
</head>
<body bgcolor="#ffffff">
<center>
<%
//文件上传的保存路径
String path = request.getRealPath("/upload");

//取得客户端上传的数据类型
String contentType = request.getContentType();
//out.println("<p>客户端上传的数据类型 = " + contentType + "</p>");

//声明文件读入类
DataInputStream in = null;
FileOutputStream fileOut = null;

try{
if(contentType.indexOf("multipart/form-data") >= 0){
//读入上传的数据
in = new DataInputStream(request.getInputStream());
int fileSize = request.getContentLength();

//定义上载文件的最大字节
int MAX_SIZE = 102400 * 102400;
if(fileSize > MAX_SIZE){
out.println("<P>上传的文件字节数不可以超过" + MAX_SIZE + "</p>");
return;
}
//保存上传文件的数据
byte dataBytes[] = new byte[fileSize];
int byteRead = 0;
int totalBytesRead = 0;
//上传的数据保存在byte数组
while(totalBytesRead < fileSize){
byteRead = in.read(dataBytes,totalBytesRead,fileSize);
totalBytesRead += byteRead;
}
//根据byte数组创建字符串
String file = new String(dataBytes);
//out.println(file);
//取得上传的数据的文件名
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
//out.println("--------------"+saveFile);
saveFile = saveFile.substring(0,saveFile.indexOf("\n"));
out.println("--------------"+saveFile);
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
out.println("--------------"+saveFile);
//创建保存路径的文件名
String fileName = path + "\\"+saveFile;
out.print("==========="+fileName);

int lastIndex = contentType.lastIndexOf("=");
//取得数据的分隔字符串
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n",pos) + 1;
pos = file.indexOf("\n",pos) + 1;
pos = file.indexOf("\n",pos) + 1;
int boundaryLocation = file.indexOf(boundary,pos) - 4;
//out.println(boundaryLocation);
//取得文件数据的开始的位置
int startPos = ((file.substring(0,pos)).getBytes()).length;
//out.println(startPos);
//取得文件数据的结束的位置
int endPos = ((file.substring(0,boundaryLocation)).getBytes()).length;
//out.println(endPos);
//检查上载文件是否存在
File checkFile = new File(fileName);
if(checkFile.exists()){
out.println("<p>" + saveFile + "文件已经存在.</p>");
return;
}
//检查上载文件的目录是否存在
File fileDir = new File(path);
if(!fileDir.exists()){
fileDir.mkdirs();
}
//创建文件的写出类
fileOut = new FileOutputStream(fileName);
//保存文件的数据
fileOut.write(dataBytes,startPos,(endPos - startPos));
fileOut.close();
out.println("<P>" + saveFile + "文件成功上载.</p>");
}else{
String content = request.getContentType();
out.println("<p>上传的数据类型不是是multipart/form-data</p>");
}
}catch(Exception ex){
throw new ServletException(ex.getMessage());
}
%>
</center>
</body>
</html>
三、文件下载(downLoad.jsp)
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import = "java.io.*" %>
<%
//防止IE缓存
response.setHeader("pragma","no-cache");
response.setHeader("cache-control","no-cache");
response.setDateHeader("Expires",0);
//设置编码
request.setCharacterEncoding("UTF-8");
String fileName = new String(request.getParameter("fileName").getBytes("ISO-8859-1"),"UTF-8");
//取到文件
File file = new File(application.getRealPath("/")+"upload/" + fileName);

response.reset();
//response.setContentType("application/octet-stream;charset=UTF-8");
response.setContentType("application/octet-stream;charset=UTF-8");//解决在弹出文件下载框不能打开文件的问题
//System.out.println(response.getCharacterEncoding());
//一定要对fileName进行encode
//response.addHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"),"ISO8859-1"));//解决在弹出文件下载框不能打开文件的问题
response.setContentLength((int) file.length());
byte[] buffer = new byte[4096];
BufferedOutputStream output = null;
BufferedInputStream input = null;

//写缓冲区
try {
output = new BufferedOutputStream(response.getOutputStream());
out.clear();
out = pageContext.pushBody();
input = new BufferedInputStream(new FileInputStream(file));
int n = (-1);
while ((n = input.read(buffer, 0, 4096)) > -1) {
output.write(buffer, 0, n);
}
response.flushBuffer();
}
catch (Exception e) {
}
finally {
if (input != null) input.close();
if (output != null) output.close();
}
%>

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/suoxl/archive/2009/05/14/4182944.aspx

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

可以多文件上传;
返回上传后的文件名;
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和不足。主要做了如下修正。

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

现在介绍下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]);
%>

使用的时候的注意事项

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

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

四、文件下载篇

1、下载链接页面download.html

页面源码如下:

<!--
文件名:download.html
作  者:纵横软件制作中心雨亦奇(zhsoft88@sohu.com)
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>下载</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<a href="jsp/do_download.jsp">点击下载</a>
</body>
</html>
2、下载处理页面do_download.jsp do_download.jsp展示了如何利用jspSmartUpload组件来下载文件,从下面的源码中就可以看到,下载何其简单。

源码如下:

<%@ page contentType="text/html;charset=gb2312"
import="com.jspsmart.upload.*" %><%
// 新建一个SmartUpload对象
SmartUpload su = new SmartUpload();
// 初始化
su.initialize(pageContext);
// 设定contentDisposition为null以禁止浏览器自动打开文件,
//保证点击链接后是下载文件。若不设定,则下载的文件扩展名为
//doc时,浏览器将自动用word打开它。扩展名为pdf时,
//浏览器将用acrobat打开。
su.setContentDisposition(null);
// 下载文件
su.downloadFile("/upload/如何赚取我的第一桶金.doc");
%>
注意,执行下载的页面,在Java脚本范围外(即<% ... %>之外),不要包含HTML代码、空格、回车或换行等字符,有的话将不能正确下载。不信的话,可以在上述源码中%><%之间加入一个换行符,再下载一下,保证出错。因为它影响了返回给浏览器的数据流,导致解析出错。

3、如何下载中文文件

jspSmartUpload虽然能下载文件,但对中文支持不足。若下载的文件名中有汉字,则浏览器在提示另存的文件名时,显示的是一堆乱码,很扫人兴。上面的例子就是这样。(这个问题也是众多下载组件所存在的问题,很少有人解决,搜索不到相关资料,可叹!)

为了给jspSmartUpload组件增加下载中文文件的支持,我对该组件进行了研究,发现对返回给浏览器的另存文件名进行UTF-8编码后,浏览器便能正确显示中文名字了。这是一个令人高兴的发现。于是我对jspSmartUpload组件的SmartUpload类做了升级处理,增加了toUtf8String这个方法,改动部分源码如下:

public void downloadFile(String s, String s1, String s2, int i)
throws ServletException, IOException, SmartUploadException
{
if(s == null)
throw new IllegalArgumentException("File '" + s +
"' not found (1040).");
if(s.equals(""))
throw new IllegalArgumentException("File '" + s +
"' not found (1040).");
if(!isVirtual(s) && m_denyPhysicalPath)
throw new SecurityException("Physical path is
denied (1035).");
if(isVirtual(s))
s = m_application.getRealPath(s);
java.io.File file = new java.io.File(s);
FileInputStream fileinputstream = new FileInputStream(file);
long l = file.length();
boolean flag = false;
int k = 0;
byte abyte0[] = new byte[i];
if(s1 == null)
m_response.setContentType("application/x-msdownload");
else
if(s1.length() == 0)
m_response.setContentType("application/x-msdownload");
else
m_response.setContentType(s1);
m_response.setContentLength((int)l);
m_contentDisposition = m_contentDisposition != null ?
m_contentDisposition : "attachment;";
if(s2 == null)
m_response.setHeader("Content-Disposition",
m_contentDisposition + " filename=" +
toUtf8String(getFileName(s)));
else
if(s2.length() == 0)
m_response.setHeader("Content-Disposition",
m_contentDisposition);
else
m_response.setHeader("Content-Disposition",
m_contentDisposition + " filename=" + toUtf8String(s2));
while((long)k < l)
{
int j = fileinputstream.read(abyte0, 0, i);
k += j;
m_response.getOutputStream().write(abyte0, 0, j);
}
fileinputstream.close();
}
/**
* 将文件名中的汉字转为UTF8编码的串,以便下载时能正确显示另存的文件名.
* 纵横软件制作中心雨亦奇2003.08.01
* @param s 原文件名
* @return 重新编码后的文件名
*/
public static String toUtf8String(String s) {
StringBuffer sb = new StringBuffer();
for (int i=0;i<s.length();i++) {
char c = s.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes("utf-8");
} catch (Exception ex) {
System.out.println(ex);
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0) k += 256;
sb.append("%" + Integer.toHexString(k).
toUpperCase());
}
}
}
return sb.toString();
}
注意源码中粗体部分,原jspSmartUpload组件对返回的文件未作任何处理,现在做了编码的转换工作,将文件名转换为UTF-8形式的编码形式。UTF-8编码对英文未作任何处理,对中文则需要转换为%XX的形式。toUtf8String方法中,直接利用Java语言提供的编码转换方法获得汉字字符的UTF-8编码,之后将其转换为%XX的形式。

将源码编译后打包成jspSmartUpload.jar,拷贝到Tomcat的shared/lib目录下(可为所有WEB应用程序所共享),然后重启Tomcat服务器就可以正常下载含有中文名字的文件了。另,toUtf8String方法也可用于转换含有中文的超级链接,以保证链接的有效,因为有的WEB服务器不支持中文链接。

小结:jspSmartUpload组件是应用JSP进行B/S程序开发过程中经常使用的上传下载组件,它使用简单,方便。现在我又为其加上了下载中文名字的文件的支持,真个是如虎添翼,必将赢得更多开发者的青睐。

作者Blog:http://blog.csdn.net/taoshuchen/

jsp实现文件上传下载功能
jspsmartupload是由www.jspsmart.com网站开发的一个可免费使用的全功能的文件上传下载组件,适于嵌入执行上传下载操作的jsp文件中。该组件有以下几个特点:
1、使用简单。在jsp文件中仅仅书写三五行java代码就可以搞定文件的上传或下载,方便。
2、能全程控制上传。利用jspsmartupload组件提供的对象及其操作方法,可以获得全部上传文件的信息(包括文件名,大小,类型,扩展名,文件数据等),方便存取。
3、能对上传的文件在大小、类型等方面做出限制。如此可以滤掉不符合要求的文件。
4、下载灵活。仅写两行代码,就能把web服务器变成文件服务器。不管文件在web服务器的目录下或在其它任何目录下,都可以利用jspsmartupload进行下载。
5、能将文件上传到数据库中,也能将数据库中的数据下载下来。这种功能针对的是mysql数据库,因为不具有通用性,所以本文不准备举例介绍这种用法。
  jspsmartupload组件可以从www.jspsmart.com网站上自由下载,压缩包的名字是jspsmartupload.zip。下载后,用winzip或winrar将其解压到tomcat的webapps目录下(本文以tomcat服务器为例进行介绍)。解压后,将webapps/jspsmartupload目录下的子目录web-inf名字改为全大写的web-inf,这样一改jspsmartupload类才能使用。因为tomcat对文件名大小写敏感,它要求web应用程序相关的类所在目录为web-inf,且必须是大写。接着重新启动tomcat,这样就可以在jsp文件中使用jspsmartupload组件了。
注意,按上述方法安装后,只有webapps/jspsmartupload目录下的程序可以使用jspsmartupload组件,如果想让tomcat服务器的所有web应用程序都能用它,必须做如下工作:
1.进入命令行状态,将目录切换到tomcat的webapps/jspsmartupload/web-inf目录下。
2.运行jar打包命令:jar cvf jspsmartupload.jar com
(也可以打开资源管理器,切换到当前目录,用winzip将com目录下的所有文件压缩成jspsmartupload.zip,然后将jspsmartupload.zip换名为jspsmartupload.jar文件即可。)
3.将jspsmartupload.jar拷贝到tomcat的shared/lib目录下。
二、相关类说明篇
㈠ file类
  这个类包装了一个上传文件的所有信息。通过它,可以得到上传文件的文件名、文件大小、扩展名、文件数据等信息。
  file类主要提供以下方法:
1、saveas作用:将文件换名另存。
原型:
public void saveas(java.lang.string destfilepathname)

public void saveas(java.lang.string destfilepathname, int optionsaveas)
其中,destfilepathname是另存的文件名,optionsaveas是另存的选项,该选项有三个值,分别是saveas_physical,saveas_virtual,saveas_auto。saveas_physical表明以操作系统的根目录为文件根目录另存文件,saveas_virtual表明以web应用程序的根目录为文件根目录另存文件,saveas_auto则表示让组件决定,当web应用程序的根目录存在另存文件的目录时,它会选择saveas_virtual,否则会选择saveas_physical。
例如,saveas("/upload/sample.zip",saveas_physical)执行后若web服务器安装在c盘,则另存的文件名实际是c:\upload\sample.zip。而saveas("/upload/sample.zip",saveas_virtual)执行后若web应用程序的根目录是webapps/jspsmartupload,则另存的文件名实际是webapps/jspsmartupload/upload/sample.zip。saveas("/upload/sample.zip",saveas_auto)执行时若web应用程序根目录下存在upload目录,则其效果同saveas("/upload/sample.zip",saveas_virtual),否则同saveas("/upload/sample.zip",saveas_physical)。
建议:对于web程序的开发来说,最好使用saveas_virtual,以便移植。
2、ismissing
作用:这个方法用于判断用户是否选择了文件,也即对应的表单项是否有值。选择了文件时,它返回false。未选文件时,它返回true。
原型:public boolean ismissing()
3、getfieldname
作用:取html表单中对应于此上传文件的表单项的名字。
原型:public string getfieldname()
4、getfilename
作用:取文件名(不含目录信息)
原型:public string getfilename()
5、getfilepathname
作用:取文件全名(带目录)
原型:public string getfilepathname
6、getfileext
作用:取文件扩展名(后缀)
原型:public string getfileext()
7、getsize
作用:取文件长度(以字节计)
原型:public int getsize()
8、getbinarydata
作用:取文件数据中指定位移处的一个字节,用于检测文件等处理。
原型:public byte getbinarydata(int index)。其中,index表示位移,其值在0到getsize()-1之间。
㈡ files类
  这个类表示所有上传文件的集合,通过它可以得到上传文件的数目、大小等信息。有以下方法:
1、getcount
作用:取得上传文件的数目。
原型:public int getcount()
2、getfile
作用:取得指定位移处的文件对象file(这是com.jspsmart.upload.file,不是java.io.file,注意区分)。
原型:public file getfile(int index)。其中,index为指定位移,其值在0到getcount()-1之间。
3、getsize
作用:取得上传文件的总长度,可用于限制一次性上传的数据量大小。
原型:public long getsize()
4、getcollection
作用:将所有上传文件对象以collection的形式返回,以便其它应用程序引用,浏览上传文件信息。
原型:public collection getcollection()
5、getenumeration
作用:将所有上传文件对象以enumeration(枚举)的形式返回,以便其它应用程序浏览上传文件信息。
原型:public enumeration getenumeration()
㈢ request类
  这个类的功能等同于jsp内置的对象request。只所以提供这个类,是因为对于文件上传表单,通过request对象无法获得表单项的值,必须通过jspsmartupload组件提供的request对象来获取。该类提供如下方法:
1、getparameter
作用:获取指定参数之值。当参数不存在时,返回值为null。
原型:public string getparameter(string name)。其中,name为参数的名字。
2、getparametervalues
作用:当一个参数可以有多个值时,用此方法来取其值。它返回的是一个字符串数组。当参数不存在时,返回值为null。
原型:public string[] getparametervalues(string name)。其中,name为参数的名字。
3、getparameternames
作用:取得request对象中所有参数的名字,用于遍历所有参数。它返回的是一个枚举型的对象。
原型:public enumeration getparameternames()
㈣ smartupload类这个类完成上传下载工作。
a.上传与下载共用的方法:
只有一个:initialize。
作用:执行上传下载的初始化工作,必须第一个执行。
原型:有多个,主要使用下面这个:
public final void initialize(javax.servlet.jsp.pagecontext pagecontext)
其中,pagecontext为jsp页面内置对象(页面上下文)。
b.上传文件使用的方法:
1、upload
作用:上传文件数据。对于上传操作,第一步执行initialize方法,第二步就要执行这个方法。
原型:public void upload()
2、save
作用:将全部上传文件保存到指定目录下,并返回保存的文件个数。
原型:public int save(string destpathname)
和public int save(string destpathname,int option)
其中,destpathname为文件保存目录,option为保存选项,它有三个值,分别是save_physical,save_virtual和save_auto。(同file类的saveas方法的选项之值类似)save_physical指示组件将文件保存到以操作系统根目录为文件根目录的目录下,save_virtual指示组件将文件保存到以web应用程序根目录为文件根目录的目录下,而save_auto则表示由组件自动选择。
注:save(destpathname)作用等同于save(destpathname,save_auto)。
3、getsize
作用:取上传文件数据的总长度
原型:public int getsize()
4、getfiles
作用:取全部上传文件,以files对象形式返回,可以利用files类的操作方法来获得上传文件的数目等信息。
原型:public files getfiles()
5、getrequest
作用:取得request对象,以便由此对象获得上传表单参数之值。
原型:public request getrequest()
6、setallowedfileslist
作用:设定允许上传带有指定扩展名的文件,当上传过程中有文件名不允许时,组件将抛出异常。
原型:public void setallowedfileslist(string allowedfileslist)
其中,allowedfileslist为允许上传的文件扩展名列表,各个扩展名之间以逗号分隔。如果想允许上传那些没有扩展名的文件,可以用两个逗号表示。例如:setallowedfileslist("doc,txt,,")将允许上传带doc和txt扩展名的文件以及没有扩展名的文件。
7、setdeniedfileslist
作用:用于限制上传那些带有指定扩展名的文件。若有文件扩展名被限制,则上传时组件将抛出异常。
原型:public void setdeniedfileslist(string deniedfileslist)
其中,deniedfileslist为禁止上传的文件扩展名列表,各个扩展名之间以逗号分隔。如果想禁止上传那些没有扩展名的文件,可以用两个逗号来表示。例如:setdeniedfileslist("exe,bat,,")将禁止上传带exe和bat扩展名的文件以及没有扩展名的文件。
8、setmaxfilesize
作用:设定每个文件允许上传的最大长度。
原型:public void setmaxfilesize(long maxfilesize)
其中,maxfilesize为为每个文件允许上传的最大长度,当文件超出此长度时,将不被上传。
9、settotalmaxfilesize
作用:设定允许上传的文件的总长度,用于限制一次性上传的数据量大小。
原型:public void settotalmaxfilesize(long totalmaxfilesize)
其中,totalmaxfilesize为允许上传的文件的总长度。
c.下载文件常用的方法
1、setcontentdisposition
作用:将数据追加到mime文件头的content-disposition域。jspsmartupload组件会在返回下载的信息时自动填写mime文件头的content-disposition域,如果用户需要添加额外信息,请用此方法。
原型:public void setcontentdisposition(string contentdisposition)
其中,contentdisposition为要添加的数据。如果contentdisposition为null,则组件将自动添加"attachment;",以表明将下载的文件作为附件,结果是ie浏览器将会提示另存文件,而不是自动打开这个文件(ie浏览器一般根据下载的文件扩展名决定执行什么操作,扩展名为doc的将用word程序打开,扩展名为pdf的将用acrobat程序打开,等等)。
2、downloadfile
作用:下载文件。
原型:共有以下三个原型可用,第一个最常用,后两个用于特殊情况下的文件下载(如更改内容类型,更改另存的文件名)。
① public void downloadfile(string sourcefilepathname)
其中,sourcefilepathname为要下载的文件名(带目录的文件全名)
② public void downloadfile(string sourcefilepathname,string contenttype)
其中,sourcefilepathname为要下载的文件名(带目录的文件全名),contenttype为内容类型(mime格式的文件类型信息,可被浏览器识别)。
③ public void downloadfile(string sourcefilepathname,string contenttype,string destfilename)
其中,sourcefilepathname为要下载的文件名(带目录的文件全名),contenttype为内容类型(mime格式的文件类型信息,可被浏览器识别),destfilename为下载后默认的另存文件名。
三、文件上传篇
㈠ 表单要求
对于上传文件的form表单,有两个要求:
1、method应用post,即method="post"。
2、增加属性:enctype="multipart/form-data"
下面是一个用于上传文件的form表单的例子:
<form method="post" enctype="multipart/form-data"
action="/jspsmartupload/upload.jsp">
<input type="file" name="myfile">
<input type="submit">
</form>

㈡ 上传的例子
1、上传页面upload.html
本页面提供表单,让用户选择要上传的文件,点击"上传"按钮执行上传操作。
页面源码如下:
<!--
文件名:upload.html
-->
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
<head>
<title>文件上传</title>
<**** http-equiv="content-type" content="text/html; charset=gb2312">
</head>
<body>
<p> </p>
<p align="center">上传文件选择</p>
<form method="post" action="jsp/do_upload.jsp"
enctype="multipart/form-data">
<input type="hidden" name="test" value="good">
<table width="75%" border="1" align="center">
<tr>
<td><div align="center">1、
<input type="file" name="file1" size="30">
</div></td>
</tr>
<tr>
<td><div align="center">2、
<input type="file" name="file2" size="30">
</div></td>
</tr>
<tr>
<td><div align="center">3、
<input type="file" name="file3" size="30">
</div></td>
</tr>
<tr>
<td><div align="center">4、
<input type="file" name="file4" size="30">
</div></td>
</tr>
<tr>
<td><div align="center">
<input type="submit" name="submit" value="上传它!">
</div></td>
</tr>
</table>
</form>
</body>
</html>

2、上传处理页面do_upload.jsp
本页面执行文件上传操作。页面源码中详细介绍了上传方法的用法,在此不赘述了。
页面源码如下:
<%--
文件名:do_upload.jsp
--%>
<%@ page contenttype="text/html; charset=gb2312" language="java"
import="java.util.*,com.jspsmart.upload.*" errorpage="" %>
<html>
<head>
<title>文件上传处理页面</title>
<**** http-equiv="content-type" content="text/html; charset=gb2312">
</head>
<body>
<%
// 新建一个smartupload对象
smartupload su = new smartupload();
// 上传初始化
su.initialize(pagecontext);
// 设定上传限制
// 1.限制每个上传文件的最大长度。
// su.setmaxfilesize(10000);
// 2.限制总上传数据的长度。
// su.settotalmaxfilesize(20000);
// 3.设定允许上传的文件(通过扩展名限制),仅允许doc,txt文件。
// su.setallowedfileslist("doc,txt");
// 4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,
jsp,htm,html扩展名的文件和没有扩展名的文件。
// su.setdeniedfileslist("exe,bat,jsp,htm,html,,");
// 上传文件
su.upload();
// 将上传文件全部保存到指定目录
int count = su.save("/upload");
out.println(count+"个文件上传成功!<br>");
// 利用request对象获取参数之值
out.println("test="+su.getrequest().getparameter("test")
+"<br><br>");
// 逐一提取上传文件信息,同时可保存文件。
for (int i=0;i<su.getfiles().getcount();i++)
{
com.jspsmart.upload.file file = su.getfiles().getfile(i);
// 若文件不存在则继续
if (file.ismissing()) continue;
// 显示当前文件信息
out.println("<table border=1>");
out.println("<tr><td>表单项名(fieldname)</td><td>"
+ file.getfieldname() + "</td></tr>");
out.println("<tr><td>文件长度(size)</td><td>" +
file.getsize() + "</td></tr>");
out.println("<tr><td>文件名(filename)</td><td>"
+ file.getfilename() + "</td></tr>");
out.println("<tr><td>文件扩展名(fileext)</td><td>"
+ file.getfileext() + "</td></tr>");
out.println("<tr><td>文件全名(filepathname)</td><td>"
+ file.getfilepathname() + "</td></tr>");
out.println("</table><br>");
// 将文件另存
// file.saveas("/upload/" + myfile.getfilename());
// 另存到以web应用程序的根目录为文件根目录的目录下
// file.saveas("/upload/" + myfile.getfilename(),
su.save_virtual);
// 另存到操作系统的根目录为文件根目录的目录下
// file.saveas("c:\\temp\\" + myfile.getfilename(),
su.save_physical);
}
%>
</body>
</html>
文件
2、下载处理页面do_download.jsp do_download.jsp展示了如何利用jspsmartupload组件来下载文件,从下面的源码中就可以看到,下载何其简单。
源码如下:
<%@ page contenttype="text/html;charset=gb2312"
import="com.jspsmart.upload.*" %><%
// 新建一个smartupload对象
smartupload su = new smartupload();
// 初始化
su.initialize(pagecontext);
// 设定contentdisposition为null以禁止浏览器自动打开文件,
//保证点击链接后是下载文件。若不设定,则下载的文件扩展名为
//doc时,浏览器将自动用word打开它。扩展名为pdf时,
//浏览器将用acrobat打开。
su.setcontentdisposition(null);
// 下载文件
su.downloadfile("/upload/如何赚取我的第一桶金.doc");
%>

注意,执行下载的页面,在java脚本范围外(即<% ... %>之外),不要包含html代码、空格、回车或换行等字符,有的话将不能正确下载。不信的话,可以在上述源码中%><%之间加入一个换行符,再下载一下,保证出错。因为它影响了返回给浏览器的数据流,导致解析出错。

3、如何下载中文文件
jspsmartupload虽然能下载文件,但对中文支持不足。若下载的文件名中有汉字,则浏览器在提示另存的文件名时,显示的是一堆乱码,很扫人兴。上面的例子就是这样。(这个问题也是众多下载组件所存在的问题,很少有人解决,搜索不到相关资料,可叹!)
为了给jspsmartupload组件增加下载中文文件的支持,我对该组件进行了研究,发现对返回给浏览器的另存文件名进行utf-8编码后,浏览器便能正确显示中文名字了。这是一个令人高兴的发现。于是我对jspsmartupload组件的smartupload类做了升级处理,增加了toutf8string这个方法,改动部分源码如下:
public void downloadfile(string s, string s1, string s2, int i)
throws servletexception, ioexception, smartuploadexception
{
if(s == null)
throw new illegalargumentexception("file ´" + s +
"´ not found (1040).");
if(s.equals(""))
throw new illegalargumentexception("file ´" + s +
"´ not found (1040).");
if(!isvirtual(s) && m_denyphysicalpath)
throw new securityexception("physical path is
denied (1035).");
if(isvirtual(s))
s = m_application.getrealpath(s);
java.io.file file = new java.io.file(s);
fileinputstream fileinputstream = new fileinputstream(file);
long l = file.length();
boolean flag = false;
int k = 0;
byte abyte0[] = new byte;
if(s1 == null)
m_response.setcontenttype("application/x-msdownload");
else
if(s1.length() == 0)
m_response.setcontenttype("application/x-msdownload");
else
m_response.setcontenttype(s1);
m_response.setcontentlength((int)l);
m_contentdisposition = m_contentdisposition != null ?
m_contentdisposition : "attachment;";
if(s2 == null)
m_response.setheader("content-disposition",
m_contentdisposition + " filename=" +
toutf8string(getfilename(s)));
else
if(s2.length() == 0)
m_response.setheader("content-disposition",
m_contentdisposition);
else
m_response.setheader("content-disposition",
m_contentdisposition + " filename=" + toutf8string(s2));
while((long)k < l)
{
int j = fileinputstream.read(abyte0, 0, i);
k += j;
m_response.getoutputstream().write(abyte0, 0, j);
}
fileinputstream.close();
}

public static string toutf8string(string s) {
stringbuffer sb = new stringbuffer();
for (int i=0;i<s.length();i++) {
char c = s.charat(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = character.tostring(c).getbytes("utf-8");
} catch (exception ex) {
system.out.println(ex);
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0) k += 256;
sb.append("%" + integer.tohexstring(k).
touppercase());
}
}
}
return sb.tostring();
}

注意源码中粗体部分,原jspsmartupload组件对返回的文件未作任何处理,现在做了编码的转换工作,将文件名转换为utf-8形式的编码形式。utf-8编码对英文未作任何处理,对中文则需要转换为%xx的形式。toutf8string方法中,直接利用java语言提供的编码转换方法获得汉字字符的utf-8编码,之后将其转换为%xx的形式。
将源码编译后打包成jspsmartupload.jar,拷贝到tomcat的shared/lib目录下(可为所有web应用程序所共享),然后重启tomcat服务器就可以正常下载含有中文名字的文件了。另,toutf8string方法也可用于转换含有中文的超级链接,以保证链接的有效,因为有的web服务器不支持中文链接。
小结:jspsmartupload组件是应用jsp进行b/s程序开发过程中经常使用的上传下载组件,它使用简单,方便

一、安装篇

  jspSmartUpload是由www.jspsmart.com网站开发的一个可免费使用的全功能的文件上传下载组件,适于嵌入执行上传下载操作的JSP文件中。该组件有以下几个特点:

1、使用简单。在JSP文件中仅仅书写三五行JAVA代码就可以搞定文件的上传或下载,方便。

2、能全程控制上传。利用jspSmartUpload组件提供的对象及其操作方法,可以获得全部上传文件的信息(包括文件名,大小,类型,扩展名,文件数据等),方便存取。

3、能对上传的文件在大小、类型等方面做出限制。如此可以滤掉不符合要求的文件。

4、下载灵活。仅写两行代码,就能把Web服务器变成文件服务器。不管文件在Web服务器的目录下或在其它任何目录下,都可以利用jspSmartUpload进行下载。

5、能将文件上传到数据库中,也能将数据库中的数据下载下来。这种功能针对的是MYSQL数据库,因为不具有通用性,所以本文不准备举例介绍这种用法。

  jspSmartUpload组件可以从www.jspsmart.com网站上自由下载,压缩包的名字是jspSmartUpload.zip。下载后,用WinZip或WinRAR将其解压到Tomcat的webapps目录下(本文以Tomcat服务器为例进行介绍)。解压后,将webapps/jspsmartupload目录下的子目录Web-inf名字改为全大写的WEB-INF,这样一改jspSmartUpload类才能使用。因为Tomcat对文件名大小写敏感,它要求Web应用程序相关的类所在目录为WEB-INF,且必须是大写。接着重新启动Tomcat,这样就可以在JSP文件中使用jspSmartUpload组件了。

  注意,按上述方法安装后,只有webapps/jspsmartupload目录下的程序可以使用jspSmartUpload组件,如果想让Tomcat服务器的所有Web应用程序都能用它,必须做如下工作:

1.进入命令行状态,将目录切换到Tomcat的webapps/jspsmartupload/WEB-INF目录下。

2.运行JAR打包命令:jar cvf jspSmartUpload.jar com

(也可以打开资源管理器,切换到当前目录,用WinZip将com目录下的所有文件压缩成jspSmartUpload.zip,然后将jspSmartUpload.zip换名为jspSmartUpload.jar文件即可。)

3.将jspSmartUpload.jar拷贝到Tomcat的shared/lib目录下。
JSP文件上传

Java 2009-07-17 13:50 阅读10 评论0
字号:

package org.whvcse.upload.impl;
import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
/**
* 文 件 名 : jsp文件上传下载<br>
*
* @author 孟德军 CopyRright (c) 2009: <a href='mak0000@msn.com'>mak0000</a> <br>
* 文件编号: 20090526<br>
* @version 1.0 <br>
* 日 期: 2009.05.26 <br>
*
*/
public interface Upload extends Serializable {
/**
* 上传
* @param request HttpServletRequest
* @return 状态信息.
* @throws Exception 运行异常
*/
public boolean upLoad(HttpServletRequest request) throws Exception;
/**
* 释放系统资源.
* @return 析构情况
* @throws Exception 运行异常.
*/
public boolean destory() throws Exception;
public String toString();
/**
* 获得最后一次错误信息
* @return 最后一次错误信息.
*/
public String getLastError();
/**
* 上传,调用前必须先设置HttpServletRequest
* @return 状态信息.
* @throws Exception 运行异常
*/
public boolean upload() throws Exception;
/**
* 启用上传日志 使用玩需调用destory()释放资源
* @param s 日志信息
* @return
* @throws Exception
*/
public String server(String s) throws Exception;
}
package org.whvcse.upload;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import org.whvcse.upload.extend.Toolkit;
import org.whvcse.upload.impl.Upload;
/**
* 文 件 名 : jsp文件上传下载<br>
*
* @author 孟德军 CopyRright (c) 2009: <a href='mak0000@msn.com'>mak0000</a> <br>
* 文件编号: 20090526<br>
* @version 1.0 <br>
* 日 期: 2009.05.26 <br>
*
*/
public class JspUpload implements Upload {
private static final long serialVersionUID = 1L;
private HttpServletRequest request = null;
private BufferedWriter writer = null;
/**
* @see #fileSize 允许上传的文件大小
*/
private long fileSize = 1024;
/**
* @see #fileName 文件名字
*/
private String fileName = null;
/**
* @see #bufferSize 设置缓冲区的大小
*/
private int bufferSize = 128;
/**
* @see #savePath 文件保存的路径
*/
private String savePath = null;
private int t = -1;
/**
* @see #check 文件约束
*/
private String[] check = null;
/**
* @see #encoding 文件编码
*/
private String encoding = "utf-8";
/**
* @see #showErrorMessage 是否显示错误信息
*/
private boolean showErrorMessage = true;
private byte[] buffer = null;
private String seperator = null;
private boolean userDefineName = false;
private String extendname;
private Vector ErrorMessage = null;
private long length = 0;
private boolean isShowLog = false;
public JspUpload() {
}
public JspUpload(String savepath) {
this.savePath = savepath;
}
public JspUpload(HttpServletRequest request) {
this.request = request;
}
public JspUpload(HttpServletRequest request, String path) {
this.request = request;
this.savePath = path;
}
public boolean isShowLog() {
return isShowLog;
}
public void setShowLog(boolean isShowLog) {
this.isShowLog = isShowLog;
try {
if (this.isShowLog)
{
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(".//upload.log", true), System
.getProperty("file.encoding")));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* @deprecated
*/
public boolean destory() throws Exception {
if (writer != null)
{
writer.close();
}
return true;
}
public boolean upLoad(HttpServletRequest request) throws Exception {
boolean status = true;
if (savePath == null) {
errorMessage("未设置保存上传文件的路径!");
}
/*
* if (this.fileName == null) { this.fileName = setFileName(); }
*/
setRequest(request);
status = execute();
return status;
}
private void errorMessage(String message) throws Exception {
if (isShowLog) {
server("Exception" + message);
}
if (showErrorMessage) {
ErrorMessage = new Vector();
ErrorMessage.add(message);
throw new Exception(message);
}
}
public boolean upload() throws Exception {
boolean status = true;
/*
* if (this.fileName == null) { this.fileName = setFileName(); }
*/
if (this.request == null) {
errorMessage(this.request.toString() + "不能为空!");
return false;
} else {
status = execute();
}
return status;
}
public String getFileName() {
return fileName;
}
/**
* 设置上传的文件名,若不设置此项,程序将自动分析文件获得文件名,建议设置<br>
* eg: test.txt
*
* @param fileName
* 文件名
*/
public void setFileName(String fileName) {
this.fileName = fileName;
userDefineName = true;
}
public long getFileSize() {
return fileSize;
}
/**
* 设置文件允许上传文件大小,默认为1024
*
* @param fileSize
* 文件大小
*/
public void setFileSize(long fileSize) {
this.fileSize = fileSize * 1024;
}
public HttpServletRequest getRequest() {
return request;
}
/**
*
* @param request
* HttpServletRequest
*/
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public String getSavePath() {
return savePath;
}
/**
* 文件存储路径,必须设置此项.
*
* @param savePath
* 文件存储路径,必须设置此项.
*/
public void setSavePath(String savePath) {
this.savePath = savePath;
}
/**
*
* @return 返回约束数组.
*/
public String[] getCheck() {
return check;
}
/**
* 为上传文件添加约束,即不允许上传的文件类型<br>
* eg:exe bmp
*
* @param s
* 存放约束的字符串数组.若连续两次设置此项,将覆盖前一次设置.默认无.
* @return 已有的约束的数目.
*/
public int addCheck(String[] s) {
if (check == null) {
check = s;
}
return check.length;
}
private boolean execute() throws Exception {
FileOutputStream out = null;
boolean status = true;
try {
buffer = new byte[bufferSize];
request.setCharacterEncoding(getEncoding());
// 获取流对象.
ServletInputStream in = request.getInputStream();
// 获取一行标志.
t = in.readLine(buffer, 0, buffer.length);
if (t != -1) {
seperator = new String(buffer, 0, t);
seperator = seperator.substring(0, 28);
t = -1;
}
// 扩展名.filename="f:\exercise\c++.cpp"
do {
t = in.readLine(buffer, 0, buffer.length);
String s = new String(buffer, 0, t);
int index = s.indexOf("filename=\"");
if (index != -1) {
s = s.substring(index + 10);
// s=f:\exercise\c++.cpp"
index = s.indexOf("\"");
s = s.substring(0, index);
String temp = s;
if (!userDefineName) {
this.fileName = Toolkit.parse(temp, true);
// setFileName(Toolkit.parse(temp, false));
}
// s=f:\exercise\c++.cpp
index = s.lastIndexOf(".");
extendname = s.substring(index);
if (check != null) {
for (int i = 0; i < check.length; i++) {
if (extendname.equals("." + check[i])) {
errorMessage("上传的文件不符合规范,请重新上传!");
break;
}
}
}
/*
* if (!userDefineName) { this.fileName = this.fileName +
* s.substring(index); // s=.cpp }
*/
t = -1;
}
} while (t != -1);
int point = this.fileName.lastIndexOf(".");
if (point != -1) {
// 读取文件内容.
out = new FileOutputStream(this.savePath + "\\" + this.fileName);
} else {
out = new FileOutputStream(this.savePath + "\\" + this.fileName
+ extendname);
}
t = in.readLine(buffer, 0, buffer.length);
String s = new String(buffer, 0, t);
int i = s.indexOf("Content-Type:");
if (i == -1) {
errorMessage("上传的不是文件");
status = false;
return status;
} else {
// 去掉一个空行.
in.readLine(buffer, 0, buffer.length);
t = -1;
}
long trancsize = 0;
t = in.readLine(buffer, 0, buffer.length);
while (t != -1) {
s = new String(buffer, 0, t);
if (s.length() > 28) {
s = s.substring(0, 28);
if (s.equals(seperator)) {
break;
}
}
if (fileSize != -1) {
if (trancsize >= (getFileSize())) {
File f = new File(this.savePath + "\\" + this.fileName
+ extendname);
f.delete();
errorMessage("上传文件过大!");
}
}
out.write(buffer, 0, t);
trancsize += t;
t = in.readLine(buffer, 0, buffer.length);
}
length = trancsize;
} catch (Exception e) {
status = false;
File f = new File(this.savePath + "\\" + this.fileName + extendname);
f.delete();
errorMessage(e.getMessage());
} finally {
if (status) {
out.close();
}
}
if (isShowLog) {
server(request.getRemoteAddr() + " upload " + this.savePath + "\\"
+ this.fileName);
}
return status;
}
public boolean isShowErrorMessage() {
return showErrorMessage;
}
public void setShowErrorMessage(boolean showErrorMessage) {
this.showErrorMessage = showErrorMessage;
}
public String getEncoding() {
return encoding;
}
/**
* 设置文件编码,可不设置.
*
* @param encoding
* 文件编码.
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
*
* @deprecated 该方法已废弃.
*/
private String setFileName() {
Calendar dt = Calendar.getInstance();
String str = "" + dt.get(Calendar.YEAR) + dt.get(Calendar.MONTH)
+ dt.get(Calendar.DAY_OF_MONTH);
str = str + dt.get(Calendar.HOUR) + dt.get(Calendar.MINUTE)
+ dt.get(Calendar.SECOND);
return str;
}
public int getBufferSize() {
return bufferSize;
}
/**
* 设置程序缓冲区的大小.
*
* @param bufferSize
* 缓冲区大小
*/
public void setBufferSize(int bufferSize) {
this.bufferSize = bufferSize;
}
public String getLastError() {
String message = null;
if (ErrorMessage == null) {
message = null;
} else {
message = (String) ErrorMessage.get(0);
ErrorMessage.remove(0);
}
return message;
}
public String toString() {
return JspUpload.class.getName();
}
/**
*
* @return 文件实际大小.KB
*/
public long length() {
return length / 1024;
}
public String server(String s) throws Exception {
writer.write(new Date().toString() + " "+s);
writer.newLine();
return s;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: