Java接收 上传文件 返回路径

2023-06-07 / 0 评论 / 20 阅读 / 正在检测是否收录...

postman测试提交

controller层

    @PostMapping(value = "/file/upload")
    @ApiOperation(value = "上传家长单图片", httpMethod = "POST")
    @ResponseBody
    public BaseResponse fileUpload(@RequestPart(value = "file") MultipartFile file) {
        if (file.isEmpty()){
            // TODO
            return BaseResponse.fail();
        }
        return BaseResponse.success(studentPickInfoService.uploadFile(file));
    }
    

service


    @Value("${upload.root-dir}")
    private String uploadRootDir;//文件路径
    @Value("${upload.root-url}")
    private String uploadRootUrl;//访问文件域名
    private final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    
    @Override
    public String uploadFile(MultipartFile file) {
        try {
            String dir = "/ask_leave/student/" + df.format(new Date()) + "/";
            String uploadRootDirPath = uploadRootDir + dir;
            File imgPath = new File(uploadRootDirPath);
            if (!imgPath.exists()) {
                imgPath.mkdirs();
            }
            if (!file.isEmpty()) {
                String originalFileName = file.getOriginalFilename();
                String suffix = getFileSuffix(originalFileName);
                String fileName = UUIDGenerator.generate() + "." + suffix;
                String filePath = uploadRootDirPath + fileName;

                System.out.println(filePath);
                System.out.println(uploadRootUrl + dir + fileName);

                file.transferTo(new File(filePath));
                return uploadRootUrl + dir + fileName;
            } else {
                throw new BusinessException(5001, "文件上传失败");
            }
        } catch (IOException e) {
            throw new BusinessException(5001, "文件上传失败");
        }
    }

    private String getFileSuffix(String fileName) {
        String suffix = "jpg";
        if (org.apache.commons.lang3.StringUtils.isNotBlank(fileName) && fileName.lastIndexOf(".") > 0) {
            String[] arrStr = fileName.split("\\.");
            suffix = arrStr[arrStr.length - 1];
        }
        return suffix;
    }
本文共 34 个字数,平均阅读时长 ≈ 1分钟
0

打赏

海报

正在生成.....

评论 (0)

取消
欢迎来到本站!