spring mvc文件上传

来源:互联网 发布:上海交通大学网络管理 编辑:程序博客网 时间:2024/05/16 13:02
@RequestMapping("public/upload")
public void upload(HttpServletRequest request,HttpServletResponse response) throws IOException {
MultipartResolver resolver = new CommonsMultipartResolver(request
.getSession().getServletContext());


MultipartHttpServletRequest multipartRequest = resolver
.resolveMultipart(request);
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
MultipartFile multipartFile = null;


for (Map.Entry<String, MultipartFile> set : fileMap.entrySet()) {
String filekey = set.getKey();// Filedata
multipartFile = set.getValue();// 文件名
}
String path = this.storeIOc(multipartRequest, multipartFile);
response.getWriter().write(path);
//return path;
}


// 接受图片,返回图片地址
@SuppressWarnings("deprecation")
private String storeIOc(HttpServletRequest request, MultipartFile file) throws IOException {
//得到项目的保存图片的路径
String webPath = request.getRealPath("/wtpp/upload/images");
Date day = new Date();
String today =  DateFormat.getDateInstance(DateFormat.DEFAULT).format(day);
File  todayFile = new File(webPath+File.separator+today);
//如果文件夹不存在,创建文件夹,文件夹以日期命名
if(!todayFile.exists()){
todayFile.mkdir();
}


String logImageName = "";
if (file.isEmpty()) {
System.out.println("文件未上传");
} else {
String _fileName = file.getOriginalFilename();
String suffix = _fileName.substring(_fileName.lastIndexOf("."));
// /**使用UUID生成文件名称**/
logImageName = UUID.randomUUID().toString() + suffix;


File restore = new File(todayFile.getAbsolutePath()+File.separator + logImageName);
try {
file.transferTo(restore);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 返回图片地址


return today +"/"+ logImageName;
}
1 0
原创粉丝点击