Springアップロードファイル
3271 ワード
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を取得しますか?