/**
* 获取当前时间 yyyyMMddHHmmss
* @return String
*/
public static String getCurrTime() {
Date now = new Date();
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String s = outFormat.format(now);
return s;
}
/**
* 取出一个指定长度大小的随机正整数.
*
* @param length
* int 设定所取出随机数的长度。length小于11
* @return int 返回生成的随机数。
*/
public static int buildRandom(int length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
}
for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}
-----------------------------------------------------------------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);
}
//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();
}
}
}
}