📄 fileupload.java
字号:
ret = 1;
files.removeAllElements();
int allFileSize = 0;
ServletInputStream in = request.getInputStream();
final int maxcount = 2048; //一行的最大字节数1024,如果设为128会使得当上传文件的路径比较长时被截断
byte[] line = new byte[maxcount];
byte[] oldline = new byte[maxcount];
int oldi;
int i = in.readLine(line, 0, maxcount);
if (debug) {
//写入文件,调试用
File f2 = new File("c:/redmoon_fileupload.txt");
FileOutputStream os2;
os2 = new FileOutputStream(f2);
while (i != -1) {
String d = new String(line, 0, i);
os2.write(d.getBytes("ISO-8859-1"));
i = in.readLine(line, 0, maxcount);
}
os2.close();
if (true) {
return -1;
}
}
if (i < 3) { // 第一行小于3则上传出错
ret = this.RET_FAIL;
return ret;
}
int boundaryLength = i - 2; // 去除换行回车
String boundary = new String(line, 0, boundaryLength); //-2是为了丢弃换行字符
fields = new Hashtable();
/**
* Web站点主目录的位置为<%=request.getRealPath("/")%>
JSP网页所在的目录位置<%=request.getRealPath("./")%>
JSP网页所在目录上一层目录的位置<%=request.getRealPath("../")%>
*/
// 检查临时文件目录是否存在,不存在,则创建
if (tmpPath==null) {
String rootPath = application.getRealPath("/");
tmpPath = rootPath + "FileUploadTmp/";
File f = new File(tmpPath);
if (!f.isDirectory()) {
f.mkdirs();
}
}
while (i != -1) {
String newLine = new String(line, 0, i); //第一行
if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {
if (newLine.indexOf("filename=\"") != -1) {
// 获取上传的文件
int pos = newLine.indexOf("name=\"");
String fieldName = newLine.substring(pos + 6,
newLine.length() - 3);
// 此时 fieldName = filename1"; filename="C:\Documents and Settings\Administrator\My Documents\My Pictures\forum_isnews.gif
int index = fieldName.indexOf("\";");
fieldName = fieldName.substring(0, index);
fieldName = new String(fieldName.getBytes(), charset);
parseFileName(new String(line, 0, i - 2, charset));
if (filename == null) {
// 未上传文件
i = in.readLine(line, 0, maxcount);
continue;
}
if (filename != null && !isValidExtname(extname)) {
if (debug) {
System.out.println("extname=" + extname);
}
ret = this.RET_INVALIDEXT; // 扩展名非法
return ret;
}
i = in.readLine(line, 0, maxcount);
setContentType(new String(line, 0, i - 2));
i = in.readLine(line, 0, maxcount); // 读空行
i = in.readLine(line, 0, maxcount);
newLine = new String(line, 0, i);
// StringBuffer filedata = new StringBuffer(1000); //文件数据
long thisfilesize = 0;
// 创建临时文件
String tmpFileName = getRandName() + "." + extname;
String tmpFilePath = tmpPath + tmpFileName;
// 记录临时文件的路径
tmpFiles.addElement(tmpFilePath);
File tmpFile = new File( tmpFilePath );
FileOutputStream os2;
os2 = new FileOutputStream(tmpFile);
while (i != -1 && !newLine.startsWith(boundary)) {
oldi = i;
for (int k = 0; k < i; k++) {
oldline[k] = line[k]; // 复制line
}
i = in.readLine(line, 0, maxcount);
if ((i == boundaryLength + 2 || i == boundaryLength + 4)
&& (new String(line, 0, i).startsWith(boundary))) { //如果是所有数据的最后一行或分界符
// filedata.append(new String(oldline, 0, oldi - 2,
// "ISO-8859-1"));
os2.write(oldline, 0, oldi-2);
allFileSize += oldi - 2;
thisfilesize += oldi - 2;
} else {
// filedata.append(new String(oldline, 0, oldi,
// "ISO-8859-1"));
os2.write(oldline, 0, oldi);
allFileSize += oldi;
thisfilesize += oldi;
}
newLine = new String(line, 0, i);
// if (filedata.length() > fileSize * 1024) { // 图片尺寸要小于fileSize K
if (thisfilesize > fileSize * 1024) {
// 此处直接退出,当文件太大时会导致客户端出现“找不到服务器”错误,可能是因为in未readline所有request中的数据而致使产生浏览器报DNS错误
in.close();
tmpFile.delete();
os2.close();
ret = this.RET_TOOLARGESINGLE;
return ret;
}
// 如果超过预定上传文件总的大小
if (maxAllFileSize != -1 &&
allFileSize > maxAllFileSize * 1024) {
ret = this.RET_TOOLARGEALL;
tmpFile.delete();
os2.close();
return ret;
}
}
//if (filedata.length()>fileSize*1024)//图片尺寸要小于fileSize
// ret = -3; //放在此处不会出现找不到服务器的DNS错误,但是如果文件很大的话就很耗资源
// 关闭临地文件写入流
os2.close();
if (thisfilesize == 0) {
if (debug) {
System.out.println("FileUpload 文件" + filename + "长度为 0 !");
}
continue;
}
FileInfo fi = new FileInfo();
fi.fieldName = fieldName;
fi.name = filename;
fi.ext = extname;
fi.setTmpFilePath(tmpFilePath);
// fi.data = filedata.toString();
fi.contentType = contentType;
fi.size = thisfilesize; // 或者filedata.length();//以K为单位
if (debug) {
System.out.println(fi.name + ": " + fi.size + " " +
fi.ext + " " + fi.contentType);
}
files.addElement(fi);
} else {
// 获取表单域的值
int pos = newLine.indexOf("name=\"");
String fieldName = newLine.substring(pos + 6,
newLine.length() - 3);
i = in.readLine(line, 0, maxcount);
i = in.readLine(line, 0, maxcount);
// System.out.println("reqeust getCharacterEncoding: " + request.getCharacterEncoding()); // 取得的值为null
newLine = new String(line, 0, i, charset);
// newLine = new String(line, 0, i);
StringBuffer fieldValue = new StringBuffer(maxcount);
while (i != -1 && !newLine.startsWith(boundary)) {
// 最后一行包含换行字符
// 因此我们必须检查当前行是否是最后一行
i = in.readLine(line, 0, maxcount);
if ((i == boundaryLength + 2 || i == boundaryLength + 4)
&& (new String(line, 0, i).startsWith(boundary))) {
fieldValue.append(newLine.substring(0,
newLine.length() - 2));
} else {
fieldValue.append(newLine);
}
// newLine = new String(line, 0, i);
newLine = new String(line, 0, i, charset);
}
// String fv = new String(fieldValue.toString().getBytes("ISO8859_1"), charset);
// fields.put(fieldName, fv);
Object obj = fields.get(fieldName);
if (obj!=null) {
// 如果为字符串
if (obj.getClass().isInstance(new String(""))) {
Vector v = new Vector();
v.addElement(obj); // 第一个对应于filed的值
v.addElement(fieldValue.toString());
fields.put(fieldName, v);
}
else {
Vector v = (Vector) obj;
v.addElement(fieldValue.toString());
}
}
else
fields.put(fieldName, fieldValue.toString());
}
}
i = in.readLine(line, 0, maxcount);
}
in.close();
return ret;
}
/**
* 写入文件
* @param isRandName 是否用随机的文件名
*/
public void writeFile(boolean isRandName) {
int size = files.size();
if (size == 0) {
return;
}
File f = new File(savePath);
if (!f.isDirectory()) {
f.mkdirs();
}
java.util.Enumeration e = files.elements();
while (e.hasMoreElements()) {
FileInfo fi = (FileInfo) e.nextElement();
if (!isRandName) {
fi.write(savePath);
} else { //防止文件名重复
fi.write(savePath,
getRandName() + "." + fi.getExt());
}
}
}
/**
* 生成唯一数字ID
* @return
*/
public static String getRandName() {
// 根据时间值,重置hash,否则hash会无限增大
if (System.currentTimeMillis()-lastRandTime>20000)
hash.clear();
Integer id = new Integer(0);
synchronized (hash) {
// 生成一个唯一的随机数字
id = new Integer(rand.nextInt());
while (hash.containsKey(id)) {
id = new Integer(rand.nextInt());
}
// 为当前用户保留该ID
String data = "";
hash.put(id, data);
}
lastRandTime = System.currentTimeMillis();
return System.currentTimeMillis() + "" + Math.abs(id.intValue());
}
/**
* 从上传的文件路径获取文件名
* Windows浏览器发送完整的文件路径和名字
* 但Linux/Unix和Mac浏览器只发送文件名字
* @param filePath String
* @param isIE bool 是否为IE
* @return String
*/
public static String getUploadFileName(String filePath) {
String fileName = "";
int pos = filePath.lastIndexOf("\\");
if (pos != -1) {
fileName = filePath.substring(pos + 1);
} else {
fileName = filePath;
}
return fileName;
}
public static String getFileExt(String fileName) {
// 下面取到的扩展名错误,只有三位,而如html的文件则有四位
// extName = fileName.substring(fileName.length() - 3, fileName.length()); //扩展名
int dotindex = fileName.lastIndexOf(".");
String extName = fileName.substring(dotindex + 1, fileName.length());
extName = extName.toLowerCase(); //置为小写
return extName;
}
private int maxAllFileSize = -1; // 等于-1表示上传总大小不受限制
private String realPath;
private static String tmpPath = null;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -