在使用Spring上传文件时,当文件过多时,会产生文件名重复的问题,所以就提出了用时间来划分文件夹来存放文件的方式,这种方式能减少产生重复文件的概率,但也有不可避免的在一个小时内上传同一个文件两次的概率,这样也会产生覆盖
public class UpLoadFile extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static final Logger LOG = Logger.getLogger(UpLoadFile.class.getName());
private int maxPostSize = 1048576000;
public void doGet(HttpServletRequest request, HttpServletResponse resopnse)
throws IOException
{
doPost(request, resopnse);
}
public void doPost(HttpServletRequest request, HttpServletResponse resopnse)
throws IOException
{
try
{
upLoad(request, resopnse);
} catch (Exception e) {
e.printStackTrace();
}
}
private void upLoad(HttpServletRequest request, HttpServletResponse resopnse)
throws Exception
{
String uploadPath = "上传文件存放的位置";
LOG.debug("uploadPath:" + uploadPath);
if (!new File(uploadPath).exists()) {
new File(uploadPath).mkdirs();
}
resopnse.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(20480);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(this.maxPostSize);
try {
List fileItems = upload.parseRequest(request);
Iterator iter = fileItems.iterator();
String fileNameSave = request.getParameter("filename");
Date date=new Date();
DateFormat format=new SimpleDateFormat("yyyyMMddHH");
String time=format.format(date);
String fileSavePath = uploadPath+time+"/";
File filePath =new File(fileSavePath);
//如果文件夹不存在则创建
if (!filePath .exists() && !filePath .isDirectory())
{
System.out.println("//不存在");
filePath .mkdir();
} else
{
System.out.println("//目录存在");
}
String exFileName = "";
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
String itemName = item.getName();
if (!item.isFormField()) {
if (itemName.indexOf(".") > 0) {
exFileName = itemName.substring(itemName
.indexOf("."));
}
fileSavePath = fileSavePath + itemName.substring(0, itemName.indexOf("."));
try {
File skFile = new File(fileSavePath + exFileName);
if (skFile.exists()) {
skFile.delete();
item.write(new File(fileSavePath + exFileName));
} else {
item.write(new File(fileSavePath + exFileName));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
resopnse.getWriter().print("newFileName:" + fileSavePath + exFileName);
LOG.debug("upload newFileName:" + fileSavePath + exFileName);
} catch (FileUploadException e) {
e.printStackTrace();
}
}
有什么好的办法避免这样的概率发生吗,上传文件和保存到数据库的文件名和url是前端传过来的,如果采用uuid的方式,怎么在保存到数据库中获取到这个uuid呢?