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

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

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

@Resource
    private YlwComponent ylwComponent;
    
@ApiOperation(value = "上传图片,返回图片url", notes = "传入 图片文件")
    @RequestMapping(value = "/uploadSup", method = RequestMethod.POST)
    public CommonResult 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 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  CommonResult success() {
        return new CommonResult(ResultCodeEnum.SUCCESS.getCode(),
                ResultCodeEnum.SUCCESS.getMessage(), null);
    }

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

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

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

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

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

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

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

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

    /**
     * 未授权返回结果
     */
    public static  CommonResult forbidden(T data) {
        return new CommonResult(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);
    }
}

你可能感兴趣的:(java,服务器,开发语言)