【发布时间】:2017-11-16 01:39:00
【问题描述】:
我正在将文件上传到文件夹,我已将文件名指定为“1.jpg”,因此当我上传新文件时,它将覆盖现有文件, 那么我如何为我正在上传的文件指定一个随机文件名
我的上传代码在这里
@RequestMapping(value = "/event/uploadFile",headers=("content-type=multipart/*"), method = RequestMethod.POST,consumes ={"application/x-www-form-urlencoded"})
//String quote_upload=C:\fakepath\images.jpg
public @ResponseBody
String uploadFileHandler(
@RequestParam MultipartFile file) {
System.out.println("Creating the directory to store file");
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator+"1.jpg");
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("************Server File Location="
+ serverFile.getAbsolutePath());
//return "You successfully uploaded file=" + name;
} catch (Exception e) {
System.out.println("************failes"+ e.getMessage());
//return "You failed to upload " + name + " => " + e.getMessage();
}
//return "You failed to upload " + name
//+ " because the file was empty.";
}
System.out.println("hello");
return "hello";
}
【问题讨论】:
-
一种选择是从
Random附加当前时间(最多秒)和随机数生成器。 -
您可以使用
java.util.UUID.randomUUID()方法为serverFile创建唯一名称