package upload;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.oreilly.servlet.multipart.FileRenamePolicy;
// 仿DefaultFileRenamePolicy public class ReFileName implements FileRenamePolicy {
public ReFileName() {
// TODO Auto-generated constructor stub
}
@Override
public File rename(File f) {
// TODO Auto-generated method stub
if (createNewFile(f)) {
return f;
}
String name = f.getName();
String body = null;
String ext = null;
int dot = name.lastIndexOf(".");
if (dot != -1) {
body = name.substring(0, dot);
ext = name.substring(dot); // includes "."
}
else {
body = name;
ext = "";
}
// Increase the count until an empty spot is found.
// Max out at 9999 to avoid an infinite loop caused by a persistent
// IOException, like when the destination dir becomes non-writable.
// We don't pass the exception up because our job is just to rename,
// and the caller will hit any IOException in normal processing.
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String dateStr = sdf.format(d); //创建时间戳字符串
int count = 0;
while (!createNewFile(f) && count < 9999) {
count++;
String newName = body + dateStr + count + ext; //文件名增加时间戳
f = new File(f.getParent(), newName);
}
return f;
}
private boolean createNewFile(File f) {
try {
return f.createNewFile();
}
catch (IOException ignored) {
return false;
}
}
}
上传界面:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>cos上传组件</title>
</head>
<body>
<!-- 多文件上传-->
<form name="form1" method="post" enctype="multipart/form-data"
action="upLoad.jsp">
<p>
<input name="file1" type="file">
</p>
<p>
<input name="file2" type="file">
</p>
<p> <input name="file3" type="file">
</p>
<p>
<input type="submit" name="Submit" value="提交 ">
</p>
</form >
</body>
</html>
提交界面:
<%@ page import="java.io.*,java.util.*"%>
<%@ page import="com.oreilly.servlet.MultipartRequest,upload.ReFileName"%>//引入
<%@ page contentType="text/html; charset=utf-8" %>
<%
String saveDirectory ="d:\\test";
//每个文件最大100m,最多10个文件,所以...
int maxPostSize =10 * 100 * 1024 * 1024;
ReFileName dfr = new ReFileName(); //创建从命名对象
//调用上传方法,将重命名类的对象,作为最后一个参数传入
MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8",dfr);
//输出反馈信息
Enumeration files = multi.getFileNames();
while (files.hasMoreElements()){
String name = (String)files.nextElement();
File f = multi.getFile(name);
if(f!=null){
String fileName = multi.getFilesystemName(name);
String lastFileName= saveDirectory+"\\" + fileName;
out.println("Upload Success:"+lastFileName);
out.println("<br>");
}
}
%>