第六阶段 第四模块
文章目录









` public ResponseResult fileUpload(@RequestParam("file")MultipartFile file, HttpServletRequest request) throws IOException {
//1.判断接收到的上传文件是否为空
if(file.isEmpty()){
throw new RuntimeException();
}
//2.获取项目部署路径
// D:\apache-tomcat-8.5.56\webapps\ssm-web\
String realPath = request.getServletContext().getRealPath("/");
// D:\apache-tomcat-8.5.56\webapps
String substring = realPath.substring(0, realPath.indexOf("ssm-web"));
//3.获取原文件名
//lagou.jpg
String originalFilename = file.getOriginalFilename();
//4.生成新文件名
//12421321.jpg
String newFileName = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
//5.文件上传
String uploadPath = substring + "upload\\";
File filePath = new File(uploadPath, newFileName);
// 如果目录不存在就创建目录
if(!filePath.getParentFile().exists()){
filePath.getParentFile().mkdirs();
System.out.println("创建目录:" + filePath);
}
// 图片就进行了真正的上传
file.transferTo(filePath);
// 6. 将文件名和文件路径返回,进行响应
Map<String, String> map = new HashMap<>();
map.put("fileName",newFileName);
map.put("filePath","http://localhost:8080/upload/" + newFileName);
ResponseResult responseResult = new ResponseResult(true, 200, "图片上传成功", map);
return responseResult;
}`





trim是用来格式化的 prefix 就是在开始加个set suffixoverrides就是去掉结尾的“ , ”










评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论