图片上传


/*
课程图片上传
*/
@RequestMapping("/courseUpload")
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;

}
posted @   langpo  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
点击右上角即可分享
微信分享提示