阿里云OSS图片上传

创建工具类

@Component
@ConfigurationProperties(prefix = "*****")//读取配置信息
@Data
public class OssTemplate {

    private String key; //访问key
    private String secret;//访问秘钥
    private String endpoint;//端点
    private String bucket;//桶名
    private String url;//访问域名

    //文件上传
    public String upload(String fileName, InputStream inputStream) {

        //创建客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, key, secret);

        //设置文件最终的路径和名称
        String objectName = "images/" + new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));

        //meta设置请求头,解决访问图片地址直接下载
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));

        //上传
        ossClient.putObject(bucket, objectName, inputStream, meta);

        //关闭客户端
        ossClient.shutdown();

        return url + "/" + objectName;
    }

    //文件后缀处理
    private String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".JPG") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        return "image/jpg";
    }
}

配置文件中添加oss配置

*****:
  oss:
    key: AccessKey ID
    secret: AccessKey Secret
    endpoint: 地域节点
    bucket: Bucket名
    url: https://bucket.secret

配置文件上传解析器

spring:
  servlet:
    multipart:
      max-request-size: 100MB # 最大请求文件大小,默认10MB
      max-file-size: 100MB # 单个请求文件大小,默认1MB

图片上传

@RestController
@Slf4j
public class FileController {

    @Autowired
    private OssTemplate ossTemplate;

    @PostMapping("请求路径")
    public ResultInfo uploadFile(MultipartFile file) throws IOException {
        String filePath = ossTemplate.upload(file.getOriginalFilename(), file.getInputStream());
        log.info("文件上传成功,访问地址是:{}", filePath);
        return ResultInfo.success(filePath);
    }
}

 

上一篇:Linux 有问必答:在Linux上如何将文本文件转换成PDF格式


下一篇:android在控制台签名apk