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;
标签:String,filePath,fileName,照片,newFileName,file,new,上传 From: https://www.cnblogs.com/zyb-luckey/p/18079589