| | |
| | | //图片上传 |
| | | @RequestMapping({"upload.do"}) |
| | | @ResponseBody |
| | | public ServerResponse upload(HttpSession session, @RequestParam(value = "upload_file", required = false) MultipartFile file, HttpServletRequest request) { |
| | | public ServerResponse upload(HttpSession session, |
| | | @RequestParam(value = "upload_file", required = false) MultipartFile file, |
| | | HttpServletRequest request) { |
| | | |
| | | // 检查文件是否为空 |
| | | if (file == null || file.isEmpty()) { |
| | | return ServerResponse.createByErrorMsg("Please select a file to upload.",request); |
| | | } |
| | | |
| | | // 获取原始文件名 |
| | | String originalFilename = file.getOriginalFilename(); |
| | | if (originalFilename == null) { |
| | | return ServerResponse.createByErrorMsg("Invalid file name",request); |
| | | } |
| | | |
| | | // 获取文件扩展名并转为小写 |
| | | String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase(); |
| | | |
| | | // 定义允许的图片格式 |
| | | String[] allowedExtensions = {"jpg", "jpeg", "png", "gif", "bmp", "webp"}; |
| | | |
| | | // 验证文件格式 |
| | | boolean isImage = false; |
| | | for (String allowedExt : allowedExtensions) { |
| | | if (allowedExt.equals(extension)) { |
| | | isImage = true; |
| | | break; |
| | | } |
| | | } |
| | | |
| | | // 如果不是图片格式 |
| | | if (!isImage) { |
| | | return ServerResponse.createByErrorMsg("Only supports uploading image format: jpg, jpeg, png, gif, bmp, webp", request); |
| | | } |
| | | |
| | | // 获取上传路径 |
| | | String path = request.getSession().getServletContext().getRealPath("upload"); |
| | | |
| | | ServerResponse serverResponse = this.iFileUploadService.upload(file, path); |
| | | |
| | | if (serverResponse.isSuccess()) { |
| | | String targetFileName = serverResponse.getData().toString(); |
| | | String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName; |
| | | |
| | | |
| | | Map fileMap = Maps.newHashMap(); |
| | | fileMap.put("uri", targetFileName); |