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;
}
}
package org.whvcse.upload.impl;
import java.io.Serializable;
import javax.servlet.http.HttpServletResponse;
/**
* 文 件 名 : 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 Download extends Serializable {
/**
* 释放系统资源.
* @return 析构情况
* @throws Exception 运行异常.
*/
public boolean destory() throws Exception;
/**
* 执行下载方法.
* @param response HttpServletResponse
* @return 执行情况
* @throws Exception 运行异常
*/
public boolean download(HttpServletResponse response) throws Exception;
/**
* 获得最后一次错误信息
* @return 最后一次错误信息.
*/
public String getLastError();
/**
*
* @return 程序名.
*/
public String toString();
/**
* 启用下载日志,若启用日志选项,使用玩需调用destory()释放资源
* @param s 日志信息
* @return
* @throws Exception
*/
public String server(String s) throws Exception;
}
package org.whvcse.download;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Vector;
import javax.servlet.http.HttpServletResponse;
import org.whvcse.upload.extend.Toolkit;
import org.whvcse.upload.extend.Toolkit2;
import org.whvcse.upload.impl.Download;
/**
* 文 件 名 : 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 JspDownload implements Download {
private static final long serialVersionUID = 1L;
/**
* HttpServletResponse
*/
private HttpServletResponse response = null;
/**
* 文件路径
*/
private String filepath = null;
private FileInputStream in = null;
/**
* 文件名
*/
private String fileName = null;
/**
* 文件类型
*/
private String contentType = null;
/**
* 文件大小
*/
private int sendSize = 128;
/**
* 配置文件路径.默认.//config//web.xml 设置Mime类型.
*/
private String configpath = ".//config//web.xml";
private BufferedWriter writer = null;
private boolean showErrorMessage = true;
/**
* 错误信息.
*/
private Vector ErrorMessage = null;
private boolean isShowLog = false;
private boolean isSetConfig = false;
private boolean isShowChinese = false;
public JspDownload() {
}
/**
*
* @param s
* 配置文件路径,该方法能解析配置文件,根据配置文件初始化各变量.
* @return 配置文件信息。
*/
public String load(String s) {
return s;
}
public String getConfigpath() {
return configpath;
}
public void setConfigpath(String configpath) {
isSetConfig = true;
this.configpath = configpath;
}
public JspDownload(String filepath, String mime) {
this.filepath = filepath;
this.contentType = mime;
}
public boolean isShowChinese() {
return isShowChinese;
}
public void setShowChinese(boolean isShowChinese) {
this.isShowChinese = isShowChinese;
}
public JspDownload(HttpServletResponse response) {
this.response = response;
}
public JspDownload(HttpServletResponse response, String filepath,
String mime) {
this.response = response;
this.filepath = filepath;
this.contentType = mime;
}
/**
* @deprecated
*/
public boolean destory() throws Exception {
if (in != null) {
in.close();
}
if (writer != null) {
writer.close();
}
return true;
}
/**
* 下载文件.
*/
public boolean download(HttpServletResponse response) throws Exception {
if (this.response == null) {
this.response = response;
}
if (this.filepath == null) {
ErrorMessage("未设置文件的路径");
}
/*
* if (this.contentType == null) { String ct =
* Toolkit.getContextType(this.filepath); if (ct != null) {
* setContentType(ct); } else { ErrorMessage("未设置文件Mime类型"); } }
*/
String mime = null;
try {
mime = Toolkit2.getContextType(this.filepath, this.configpath);
if (mime != null) {
setContentType(mime);
} else {
ErrorMessage("未设置Content-Type");
}
} catch (RuntimeException e) {
ErrorMessage(e.getMessage());
}
if (this.response == null) {
ErrorMessage("HttpServletResponse初始化失败");
}
return execute();
}
/**
* 下载文件.调用前必须设置HttpServletResponse
*/
public boolean download() throws Exception {
if (this.filepath == null) {
ErrorMessage("未设置文件保存路径");
}
String mime = null;
try {
mime = Toolkit2.getContextType(this.filepath, this.configpath);
if (mime != null) {
setContentType(mime);
} else {
ErrorMessage("未设置Content-Type");
}
} catch (RuntimeException e) {
ErrorMessage(e.getMessage());
}
if (this.response == null) {
ErrorMessage("HttpServletResponse初始化失败");
}
return execute();
}
private boolean execute() throws Exception {
boolean status = true;
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[this.sendSize];
File fileload = new File(this.filepath);
// 客户端使用保存文件的对话框.
if (this.fileName == null) {
this.fileName = Toolkit.parse(this.filepath, true);
}
if (isShowChinese) {
response.setHeader("Content-disposition", "attachment;filename="
+ Toolkit2.toChinese(this.fileName));
} else {
response.setHeader("Content-disposition", "attachment;filename="
+ this.fileName);
}
// 设置Mime类型.
response.setContentType(this.contentType);
// 通知文件的长度.
long fileLength = fileload.length();
String length = String.valueOf(fileLength);
response.setHeader("Content_Length", length);
// 读取文件.
try {
in = new FileInputStream(fileload);
int n = 0;
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
}
out.flush();
} catch (RuntimeException e) {
ErrorMessage(e.getMessage());
status = false;
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
if (isShowLog) {
server(" down " + this.filepath);
}
return status;
}
/**
* 返回最后一次发生错误的描述.<br>
*
* @see #getLastError() 返回最后一次错误的描述.
*/
public String getLastError() {
String message = null;
if (ErrorMessage == null) {
return message = null;
} else {
message = (String) ErrorMessage.get(0);
ErrorMessage.remove(0);
}
return message;
}
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 String getFilepath() {
return filepath;
}
/**
* 设置文件路径.<br>
*
* @param filepath
* 文件路径.
*/
public void setFilepath(String filepath) {
this.filepath = filepath;
}
/**
* @deprecated 返回文件Mime类型.<br>
* @return 文件Mime类型.
*/
public String getMime() {
return contentType;
}
/**
* @deprecated 设置文件Mime类型.<br>
* @param mime
* 文件Mime类型.
*/
public void setMime(String mime) {
this.contentType = mime;
}
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
/**
* 异常是否已经显示.
*
* @return 异常是否已经显示.
*/
public boolean isShowErrorMessage() {
return showErrorMessage;
}
/**
* 是否显示异常信息.<br>
*
* @param showErrorMessage
* 是否显示异常.
*/
public void setShowErrorMessage(boolean showErrorMessage) {
this.showErrorMessage = showErrorMessage;
}
@Override
public String toString() {
return JspDownload.class.getName();
}
public boolean isShowLog() {
return isShowLog;
}
public void setShowLog(boolean isShowLog) {
try {
this.isShowLog = isShowLog;
if (this.isShowLog) {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(".//down.log", true), System
.getProperty("file.encoding")));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public int getSendSize() {
return sendSize;
}
public void setSendSize(int sendSize) {
this.sendSize = sendSize;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String server(String s) throws Exception {
writer.write(new Date().toString() + s);
writer.newLine();
return s;
}
}
package org.whvcse.upload.extend;
/**
* 文 件 名 : 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 Toolkit {
/**
*
* @param filename
* 文件路径.
* @param isshowextendname
* 是否解析扩展名.
* @return 文件名
*/
public static String parse(String filename, boolean isshowextendname) {
String name = null;
int index = filename.lastIndexOf(".");
int extendindex = filename.lastIndexOf("\\");
if (index != -1 && extendindex != -1) {
if (isshowextendname) {
name = filename.substring(extendindex + 1);
} else {
name = filename.substring(extendindex + 1, index);
}
}
return name;
}
/**
*
* @param filename
* 文件名
* @return Mime类型
*/
public static String getContextType(String filename) {
String file = parse(filename, true);
String Mime = null;
if (file != null) {
if (file.lastIndexOf(".html") != -1
|| file.lastIndexOf(".htm") != -1) {
Mime = "text/html";
}
if (file.lastIndexOf(".txt") != -1) {
Mime = "text/plain";
}
if (file.lastIndexOf(".gif") != -1) {
Mime = "image/gif";
}
if (file.lastIndexOf(".jpg") != -1
|| file.lastIndexOf(".jpeg") != -1) {
Mime = "image/jpeg";
}
if (file.lastIndexOf(".tar") != -1) {
Mime = "application/x-tar";
}
if (file.lastIndexOf(".gz") != -1) {
Mime = "application/x-gzip";
}
if (file.lastIndexOf(".avi") != -1) {
Mime = "video/x-msvideo";
}
if (file.lastIndexOf(".mpg") != -1
|| file.lastIndexOf(".mpeg") != -1) {
Mime = "video/mpeg";
}
if (file.lastIndexOf(".xml") != -1) {
Mime = "text/xml";
}
if (file.lastIndexOf(".css") != -1) {
Mime = "text/css";
}
if (file.lastIndexOf(".ttf") != -1) {
Mime = "application/octet-stream";
}
if (file.lastIndexOf(".pdf") != -1) {
Mime = "application/pdf";
}
if (file.lastIndexOf("zip") != -1) {
Mime = "application/zip";
}
}
return Mime;
}
/**
*
* @param s
* 需要转换的编码.
* @return base64编码后的字符串.
*/
public static String Encode(String s) {
String old = null;
if (s == "" || s.equals("")) {
old = "";
}
try {
old = new sun.misc.BASE64Encoder().encode(s.getBytes());
// old=new sun.misc.BASE64Decoder().decodeBuffer(arg0)
} catch (Exception e) {
e.printStackTrace();
}
return old;
}
/**
*
* @param s
* 需要转换的编码.
* @return 解码后的字符串.
*/
public static String DeEncode(String s) {
String old = null;
if (s == "" || s.equals("")) {
old = "";
}
try {
old = new String(new sun.misc.BASE64Decoder().decodeBuffer(s));
} catch (Exception e) {
e.printStackTrace();
}
return old;
}
}
package org.whvcse.upload.extend;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class Toolkit2 extends Toolkit {
/**
* 自动从配置文件中解析文件所属的Mime类型.
*
* @param filename文件名
* @param path
* 配置文件路径
* @return 解析后的Mime类型
* @throws Exception
* 配置文件错误.
*/
public static String getContextType(String filename, String path)
throws Exception {
String Mime = null;
String extension = null;
if (filename.equals(null) || path.equals(null) || filename == ""
|| path == "") {
throw new Exception("加载文件错误,文件名或配置文件路径不能为空,请检查配置文件!");
}
int index = filename.lastIndexOf(".");
extension = filename.substring(index + 1);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(path);
NodeList list = document.getElementsByTagName("mime-mapping");
Element element = null;
for (int i = 0; i < list.getLength(); i++) {
element = (Element) list.item(i);
// System.out.println(extension);
// System.out.println(extension.equals("ai"));
if (extension.equals(element.getElementsByTagName("extension")
.item(0).getFirstChild().getNodeValue())) {
Mime = element.getElementsByTagName("mime-type").item(0)
.getFirstChild().getNodeValue();
break;
}
}
return Mime;
}
/**
*
* @param source
* 需要转换的字符串.
* @return 中文编码.
*/
public static String toChinese(String source) {
String newString = null;
if (source == null) {
newString = "";
} else {
try {
newString = new String(source.getBytes("UTF-8"), "GB2312");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return newString;
}
/**
*
* @param source
* 需要转换的字符串.
* @param charset1
* 元编码
* @param charset2
* 新编码
* @return
*/
public static String charset(String source, String charset1, String charset2) {
String newString = null;
if (source == null) {
newString = "";
} else {
try {
newString = new String(source.getBytes(charset1), charset2);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return newString;
}
}