spring mvc怎么获取上传文件的原路径
2个回答
展开全部
@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");
}
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");
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询