根据时间随机数生成随机文件名 ,SpringMVC 上传文件
public static String generateRandomFilename(){String fourRandom = "";
//产生4位的随机数(不足4位前加零)
int randomNum = (int)(Math.random()*10000);
fourRandom = randomNum +"";
int randLength = fourRandom.length();
if(randLength <4){
for(int i=1; i <=4-randLength; i++)
fourRandom = fourRandom + "0";
}
StringBuilder sb = new StringBuilder("");
sb.append(CalendarUtil.getYear())
.append(twoNumbers(CalendarUtil.getMonth()))
.append(twoNumbers(CalendarUtil.getDayOfMonth()))
.append(twoNumbers(CalendarUtil.getHour()))
.append(twoNumbers(CalendarUtil.getMinute()))
.append(twoNumbers(CalendarUtil.getSecond()))
.append(fourRandom);
return sb.toString();
}
private static String twoNumbers(int number){
String _number = number + "";
if(_number.length() < 2){
_number = "0" + _number;
}
return _number;
}
-----------------------------------------------------------------SpringMVC上传文件
@RequestMapping(value = "/doAdd", method = RequestMethod.POST)
public String doAdd(@RequestParam("imgFile") MultipartFile file, HttpServletRequest request, WaterSingle waterSingle) {
if(null != file){
if(StringUtils.isEmpty(file.getOriginalFilename())){
waterSingle.setWaterName("");
}else{
String realFileName = file.getOriginalFilename();
realFileName = Utils.generateRandomFilename() + realFileName.substring(realFileName.lastIndexOf("."));
String path = GlobalStatic.uploadFilePath5 + realFileName;
Utils.uploadfile(file, path);
User user = (User) getSession().getAttribute("currentUser");
waterSingle.setWaterName(realFileName);
waterSingle.setUserName("登录名:" + user.getLoginName() + ",真实姓名:"+user.getTrueName());
waterSingle.setUploadTime(new Date());
}
waterSingleService.addWaterSingle(waterSingle);
}
return "redirect:/watersingle/list";
}
public static boolean uploadfile(MultipartFile file,String fileFullName){
try {
FileOutputStream fileOutputStream=new FileOutputStream(new java.io.File(fileFullName));
InputStream fis=file.getInputStream();
byte[] buff=new byte[1024];
@SuppressWarnings("unused")
int length=0;
while((length=fis.read(buff))>0){
fileOutputStream.write(buff);
}
fileOutputStream.flush();
fileOutputStream.close();
fis.close();
return true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
} catch (IOException e)
{
throw new RuntimeException(e);
} www.zzzyk.com
//return false;
}
public static void copyFile(File src, File dst) {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
作者:gdn_wolf
补充:软件开发 , Java ,