/**
* 文件上传
*
* @param file 文件
* @param uploadPath 上传路径
* @param filePath 文件路径
* @return
*/
private String upload(MultipartFile file, String uploadPath, String filePath) {
FileOutputStream fos = null;
File filePathDir = new File(uploadPath);
if (!filePathDir.exists()) {
filePathDir.mkdirs();
}
String fileName = StringUtil.getUUid() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String path = uploadPath + fileName;
File f = new File(path);
try {
fos = new FileOutputStream(f);
fos.write(file.getBytes(), 0, file.getBytes().length); //上传
} catch (Exception e) {
throw new GlobalException("上传失败");
} finally {
try {
if (null != fos) {
fos.flush();
fos.getFD().sync();
fos.close();
}
} catch (IOException e) {
throw new GlobalException("上传失败");
}
}
return filePath + fileName;
}
@Controller
public class FileUploadController {
private static String UPLOAD_DIRECTORY = PropertiesUtil.get("fileupload.directory", "");
@RequestMapping(value = "uploadFile", method = RequestMethod.POST)
public ModelAndView uploadFile(@RequestParam("file") MultipartFile file){
// 判断文件是否为空
if (!file.isEmpty()) {
try {
//判断文件目录是否存在,否则自动生成
File directory = new File(UPLOAD_DIRECTORY);
if (!directory.exists()){
directory.mkdirs();
}
//失败跳转视图
if (file.getSize() > 30000)
return new ModelAndView("uploadFail","msg",file.getOriginalFilename()+"超过了指定大小");
// 文件保存路径
String filePath = FilenameUtils.concat(UPLOAD_DIRECTORY, file.getOriginalFilename());
// 转存文件
file.transferTo(new File(filePath)); //上传
} catch (Exception e) {
e.printStackTrace();
}
}
//成功跳转视图
return new ModelAndView("uploadSuccess","msg",file.getOriginalFilename());
}
}