照片上传

Web层:PromotionAdController
@RestController
@RequestMapping("/PromotionSpace")
public class PromotionSpaceController {
@Autowired
private PromotionSpaceService promotionSpaceService;
/*
文件上传
*/
@RequestMapping("/PromotionAdUpload")
public ResponseResult fileupload(@RequestParam("file") MultipartFile file,
HttpServletRequest request) throws IOException {
Postman测试接口
6. 新建&修改广告(自行完成)
1.1 需求分析
新建需求:点击提交按钮,将页面内容保存到数据库
try {
//1.判断文件是否为空
if (file.isEmpty()) {
throw new RuntimeException();
}
//2.获取项目部署路径
String realPath = request.getServletContext().getRealPath("/");
String webappsPath = realPath.substring(0,
realPath.indexOf("ssm_web"));
//3.获取原文件名
String fileName = file.getOriginalFilename();
//4.新文件名
String newFileName = System.currentTimeMillis() +
fileName.substring(fileName.lastIndexOf("."));
//5.上传文件
String uploadPath = webappsPath + "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", LOCAL_URL + "/upload/" + newFileName);
ResponseResult result = new ResponseResult(true, 200, "响应成功",
map);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
Web层:PromotionAdController @RestController @RequestMapping("/PromotionSpace") public class PromotionSpaceController { @Autowired private PromotionSpaceService promotionSpaceService; /* 文件上传 */ @RequestMapping("/PromotionAdUpload") public ResponseResult fileupload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException { Postman测试接口 6. 新建&修改广告(自行完成) 1.1 需求分析 新建需求:点击提交按钮,将页面内容保存到数据库 try { //1.判断文件是否为空 if (file.isEmpty()) { throw new RuntimeException(); } //2.获取项目部署路径 String realPath = request.getServletContext().getRealPath("/"); String webappsPath = realPath.substring(0, realPath.indexOf("ssm_web")); //3.获取原文件名 String fileName = file.getOriginalFilename(); //4.新文件名 String newFileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf(".")); //5.上传文件 String uploadPath = webappsPath + "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", LOCAL_URL + "/upload/" + newFileName); ResponseResult result = new ResponseResult(true, 200, "响应成功", map); return result; } catch (Exception e) { e.printStackTrace(); } return null;
posted @   langpo  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
点击右上角即可分享
微信分享提示