spring mvc怎么获取上传文件的原路径

2025-01-05 03:57:02
推荐回答(2个)
回答1:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response) throws Exception {

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd/HH");
/** 构建文件保存的目录* */
String logoPathDir = "/business/shops/upload/"
+ dateformat.format(new Date());
/** 得到文件保存目录的真实路径* */
String logoRealPathDir = request.getSession().getServletContext()
.getRealPath(logoPathDir);
/** 根据真实路径创建目录* */
File logoSaveFile = new File(logoRealPathDir);
if (!logoSaveFile.exists())
logoSaveFile.mkdirs();
/** 页面控件的文件流* */
MultipartFile multipartFile = multipartRequest.getFile("file");
/** 获取文件的后缀* */
String suffix = multipartFile.getOriginalFilename().substring(
multipartFile.getOriginalFilename().lastIndexOf("."));
/** 使用UUID生成文件名称* */
String logImageName = UUID.randomUUID().toString() + suffix;// 构建文件名称
/** 拼成完整的文件保存路径加文件* */
String fileName = logoRealPathDir + File.separator + logImageName;
File file = new File(fileName);
try {
multipartFile.transferTo(file);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/** 打印出上传到服务器的文件的绝对路径* */
System.out.println("****************"+fileName+"**************");
insertDate(fileName);
return new ModelAndView("redirect:/business/shops/my.jsp");
}

回答2:

将文件转换为CommonsMultipartFile类型然后file.getFileItem().getName();即可