SpringBoot 整合阿里云 OSS 对象存储实现文件上传

1. 在Maven项目中加入依赖项:


    com.aliyun.oss
    aliyun-sdk-oss
    3.15.1

2. 获取配置参数

(1)获取 endpoint、accessKeyId 、accessKeySecret,通过以下位置获取 

SpringBoot 整合阿里云 OSS 对象存储实现文件上传_第1张图片

SpringBoot 整合阿里云 OSS 对象存储实现文件上传_第2张图片

SpringBoot 整合阿里云 OSS 对象存储实现文件上传_第3张图片

  (2)获取 bucket 名称,以及自定义存储在 bucket 的路径名

SpringBoot 整合阿里云 OSS 对象存储实现文件上传_第4张图片

(3)可以访问OSS中文件的公网域名host:SpringBoot 整合阿里云 OSS 对象存储实现文件上传_第5张图片

将获取到的六个参数,存储到 SpringBoot 项目中的 file.properties 文件:

file.endpoint=oss-cn-hangzhou.aliyuncs.com
file.accessKeyId=LTAI4FdvWvHhiLXUuQGToj88
file.accessKeySecret=xxxxxxxxxxxx
file.bucketName=didiok
file.objectName=images
file.ossHost=https://didiok.oss-cn-hangzhou.aliyuncs.com/

3. 新建 FileUpload.java, 如下:

@Component
@PropertySource("classpath:file.properties")
@ConfigurationProperties(prefix = "file")
public class FileUpload {

    private String endpoint;

    private String accessKeyId;

    private String accessKeySecret;

    private String bucketName;

    private String objectName;

    private String ossHost;

    // get、set 方法省略
}

4. service层类:OssServiceImpl.java

@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private FileUpload fileUpload;

    @Override
    public String uploadImg(MultipartFile file, String userId, String fileName) {

        String objectName = fileUpload.getObjectName() + "/" + userId + "/" + fileName;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(fileUpload.getEndpoint(), fileUpload.getAccessKeyId(), fileUpload.getAccessKeySecret());
        PutObjectResult result = null;
        try {
            InputStream inputStream = file.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(fileUpload.getBucketName(), objectName, inputStream);
            // 设置该属性可以返回response。如果不设置,则返回的response为空。
            putObjectRequest.setProcess("true");
            // 创建PutObject请求。
            result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            oe.printStackTrace();
        } catch (ClientException ce) {
            ce.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return result != null ? result.getResponse().getUri() : null;
    }
}

5. controller层类:OssController.java


@RestController
@RequestMapping("oss")
public class OssController {

    @Autowired
    private OssService ossService;

    @PostMapping("uploadImg")
    public DIDIOKJSONResult uploadImg(
            String userId,
            MultipartFile file,
            HttpServletRequest request, HttpServletResponse response){

        if(file == null){
            return DIDIOKJSONResult.errorMsg("文件不能为空");
        }

        String fileName = file.getOriginalFilename();
        String filePath = null;
		
        if(StringUtils.isNotEmpty(fileName)){
            String fileNameArr[] = fileName.split("\\.");
            String suffix = fileNameArr[fileNameArr.length - 1];

            if(!(suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("jpeg"))){
                return DIDIOKJSONResult.errorMsg("图片格式不正确");
            }
            filePath = ossService.uploadImg(file, userId, fileName);

        }
        if(StringUtils.isNotBlank(filePath)) {
            Users user = centerUserService.updateImg(userId, filePath);
			return DIDIOKJSONResult.ok(user);
        }
        return DIDIOKJSONResult.errorMsg("");
    }
}

6. 测试

上传图片之后返回的路径为:

http://didiok.oss-cn-hangzhou.aliyuncs.com/images/1908017YR51G1XWH/zombiehunters.png

参考资料:如何使用JavaSDK上传文件_对象存储-阿里云帮助中心

你可能感兴趣的:(阿里云,maven,云计算)