SpringBoot实现图片上传服务器并返回路径

SpringBoot实现图片上传服务器并返回路径

1.创建controller类,传入文件流

@Resource
    private YlwComponent ylwComponent;
    
@ApiOperation(value = "上传图片,返回图片url", notes = "传入 图片文件")
    @RequestMapping(value = "/uploadSup", method = RequestMethod.POST)
    public CommonResult<String> uploadSup(@RequestParam MultipartFile file) {

        if (file.isEmpty()) {
            return CommonResult.validateFailed("上传图片为空!");
        }

        String url = ylwComponent.uploadFile(file);

        if (!StringUtils.isEmpty(url)) {
            return CommonResult.success(url);
        }

        return CommonResult.failed("服务器错误,请联系管理员!");
    }

2.uploadFile详解实现文件服务器端处理

@Component
public class YlwComponent {
 @Value("${path.root}")
    private String rootPath;

 @Value("${path.resource}")
    private String resourcePath;
    
public String uploadFile(MultipartFile mf) {
        try {
            String fileName = mf.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            Date d = new Date();
            SimpleDateFormat formatter= new SimpleDateFormat("yyyyMM");
            String dStr = formatter.format(d);
            String fileNewName = Long.toString(d.getTime()) +new Random().nextInt(8999)+1000+suffix;
            String filePath = rootPath + resourcePath + dStr + File.separator + fileNewName;
            File fileDir = new File(rootPath + resourcePath + dStr);
            if(!fileDir.exists()){
                fileDir.mkdir();
            }
            File file = new File(filePath);
            mf.transferTo(file);
            return (resourcePath+ dStr + File.separator + fileNewName).replace("\\","/");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
  }

3.resourcePath,rootPath值讲解

服务器端上传文件位置的配置(application.yml)
root,resource自己随便写只需要与2步骤中保持一致即可
在这里插入图片描述
4.调用接口返回的是图片在服务器上面的路径,前端人员只需要拼接自己部署项目服务器的ip+端口+接口返回的路径即可在服务器端进行图片的渲染
5.CommonResult内容

public class CommonResult<T> implements Serializable {

    /**
     * 结果码
     */
    @ApiModelProperty(value = "结果码")
    private Long code;

    /**
     * 提示信息
     */
    @ApiModelProperty(value = "提示信息")
    private String message;

    /**
     * 返回数据
     */
    @ApiModelProperty(value = "返回数据")
    private T data;

    protected CommonResult() {
    }

    private CommonResult(long code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    /**
     * 返回成功结果
     */
    public static <T> CommonResult<T> success() {
        return new CommonResult<T>(ResultCodeEnum.SUCCESS.getCode(),
                ResultCodeEnum.SUCCESS.getMessage(), null);
    }

    /**
     * 成功返回结果
     *
     * @param data 获取的数据
     */
    public static <T> CommonResult<T> success(T data) {
        return new CommonResult<T>(ResultCodeEnum.SUCCESS.getCode(),
                ResultCodeEnum.SUCCESS.getMessage(), data);
    }

    /**
     * 成功返回结果
     *
     * @param data    获取的数据
     * @param message 提示信息
     */
    public static <T> CommonResult<T> success(T data, String message) {
        return new CommonResult<T>(ResultCodeEnum.SUCCESS.getCode(), message, data);
    }

    /**
     * 失败返回结果
     *
     * @param errorCode 错误码
     */
    private static <T> CommonResult<T> failed(IErrorCode errorCode) {
        return new CommonResult<T>(errorCode.getCode(), errorCode.getMessage(), null);
    }

    /**
     * 失败返回结果
     *
     * @param message 提示信息
     */
    public static <T> CommonResult<T> failed(String message) {
        return new CommonResult<T>(ResultCodeEnum.FAILED.getCode(),
                message, null);
    }

    /**
     * 失败返回结果
     */
    public static <T> CommonResult<T> failed() {
        return failed(ResultCodeEnum.FAILED);
    }

    /**
     * 参数验证失败返回结果
     */
    public static <T> CommonResult<T> validateFailed() {
        return failed(ResultCodeEnum.VALIDATE_FAILED);
    }

    /**
     * 参数验证失败返回结果
     *
     * @param message 提示信息
     */
    public static <T> CommonResult<T> validateFailed(String message) {
        return new CommonResult<T>(ResultCodeEnum.VALIDATE_FAILED.getCode(),
                message, null);
    }

    /**
     * 未登录返回结果
     */
    public static <T> CommonResult<T> unauthorized(T data) {
        return new CommonResult<T>(ResultCodeEnum.UNAUTHORIZED.getCode(),
                ResultCodeEnum.UNAUTHORIZED.getMessage(), data);
    }

    /**
     * 未授权返回结果
     */
    public static <T> CommonResult<T> forbidden(T data) {
        return new CommonResult<T>(ResultCodeEnum.FORBIDDEN.getCode(),
                ResultCodeEnum.FORBIDDEN.getMessage(), data);
    }

    public Long getCode() {
        return code;
    }

    public void setCode(Long code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "CommonResult{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        CommonResult<?> that = (CommonResult<?>) o;
        return Objects.equals(code, that.code) &&
                Objects.equals(message, that.message) &&
                Objects.equals(data, that.data);
    }

    @Override
    public int hashCode() {
        return Objects.hash(code, message, data);
    }
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
非常感谢您的提问!以下是Springboot实现PDF图片上传服务器并保存路径到数据库的完整代码: @Controller public class FileUploadController { @Autowired private FileUploadService fileUploadService; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file, Model model) { String fileName = StringUtils.cleanPath(file.getOriginalFilename()); String fileType = file.getContentType(); String fileExtension = FilenameUtils.getExtension(fileName); if (fileType.equals("application/pdf") && fileExtension.equals("pdf")) { try { String filePath = fileUploadService.saveFile(file); model.addAttribute("message", "File uploaded successfully!"); model.addAttribute("filePath", filePath); } catch (IOException e) { model.addAttribute("message", "File upload failed: " + e.getMessage()); } } else { model.addAttribute("message", "Please upload a PDF file!"); } return "uploadStatus"; } } @Service public class FileUploadService { @Value("${file.upload-dir}") private String uploadDir; @Autowired private FileRepository fileRepository; public String saveFile(MultipartFile file) throws IOException { String fileName = StringUtils.cleanPath(file.getOriginalFilename()); String filePath = uploadDir + "/" + fileName; File newFile = new File(filePath); newFile.getParentFile().mkdirs(); file.transferTo(newFile); FileEntity fileEntity = new FileEntity(); fileEntity.setFileName(fileName); fileEntity.setFilePath(filePath); fileRepository.save(fileEntity); return filePath; } } @Entity @Table(name = "files") public class FileEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "file_name") private String fileName; @Column(name = "file_path") private String filePath; // getters and setters } 在这个代码中,我们使用了Springboot的MultipartFile来处理上传的文件,然后通过FileUploadService将文件保存到服务器上,并将文件路径保存到数据库中。同时,我们也对上传的文件进行了一些限制,只允许上传PDF文件。如果上传的文件不符合要求,我们会返回一个错误信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无心 码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值