Spring Cloud Alibaba中的OSS对象存储:如何使用OSS进行文件存储和管理

算法之美 2019-04-12T21:24:00+08:00
0 0 216

随着云计算和大数据的兴起,企业对于文件存储和管理的需求也越来越大。阿里云对象存储服务(OSS)作为一种高可靠、高扩展性的云存储服务,被越来越多的企业所采用。而在Spring Cloud Alibaba框架中,我们也可以很方便地集成OSS对象存储,实现文件的存储和管理。

准备工作

在使用OSS之前,我们需要先在阿里云上开通OSS服务,并获取到AccessKey ID和AccessKey Secret,作为连接OSS服务的凭据。

首先,我们需要在pom.xml文件中添加以下依赖:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-oss</artifactId>
    <version>2.2.3.RELEASE</version>
</dependency>

接下来,我们需要在application.yml文件中配置OSS相关参数:

# OSS配置
aliyun:
  access-key-id: <your-access-key-id> # 阿里云AccessKey ID
  access-key-secret: <your-access-key-secret> # 阿里云AccessKey Secret
  oss:
    endpoint: http://oss-cn-hangzhou.aliyuncs.com # OSS服务的Endpoint
    bucket-name: <your-bucket-name> # OSS服务的Bucket名称

文件上传

在Spring Cloud Alibaba框架中,可以通过@EnableOssResourceConfig注解来启用OSS资源配置。

首先,我们需要创建一个OSS文件上传的接口:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.cloud.oss.annotation.OssParameter;
import com.alibaba.cloud.oss.annotation.OssUrlEncoded;
import com.alibaba.fastjson.JSONObject;

@RestController
public class OssController {

    @PostMapping("/upload")
    public JSONObject uploadFile(@RequestPart("file") MultipartFile file) {
        JSONObject result = new JSONObject();
        try {
            // 获取OSS文件名
            String filename = file.getOriginalFilename();
            
            // 上传文件到OSS
            String ossUrl = OSSUtil.upload(filename, file.getBytes());
            result.put("status", "success");
            result.put("url", ossUrl);
        } catch (Exception e) {
            result.put("status", "failed");
            result.put("message", e.getMessage());
        }
        return result;
    }
}

接下来,我们需要创建OSSUtil类来封装OSS的文件上传逻辑:

import com.alibaba.cloud.oss.OssTemplate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OSSUtil {

    @Autowired
    private OssTemplate ossTemplate;

    public String upload(String filename, byte[] content) {
        // 上传文件到OSS
        String ossUrl = ossTemplate.upload(filename, content);
        return ossUrl;
    }
}

现在,我们就可以通过调用/upload接口来实现文件上传了。调用接口时,需要传入一个MultipartFile类型的文件参数。

文件下载

接下来,我们来实现文件的下载功能。同样,我们需要创建一个OSS文件下载的接口:

import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.cloud.oss.annotation.OssParameter;
import com.alibaba.cloud.oss.annotation.OssUrlEncoded;

@Controller
@RequestMapping("/download")
public class OssDownloadController {

    @GetMapping("/{filename}")
    public ResponseEntity downloadFile(@PathVariable("filename") @OssUrlEncoded String filename) {
        Resource resource = OSSUtil.download(filename);
        if (resource == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 获取文件名
        String fileName = StringUtils.getFilename(filename);
        
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .body(resource);
    }
}

在上述代码中,我们通过@OssUrlEncoded注解来对文件名进行URL编码,以避免在文件名中包含特殊字符时出现问题。

客户端可以通过调用/download/{filename}接口来下载文件,其中{filename}为需要下载的文件名。

文件删除

最后,我们还需要实现文件的删除功能。同样,我们需要创建一个OSS文件删除的接口:

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.cloud.oss.annotation.OssParameter;

@RestController
public class OssDeleteController {

    @DeleteMapping("/{filename}")
    public String deleteFile(@PathVariable("filename") @OssParameter String filename) {
        boolean success = OSSUtil.delete(filename);
        if (success) {
            return "删除文件成功";
        } else {
            return "删除文件失败";
        }
    }
}

在上述代码中,我们通过@OssParameter注解来表示需要进行URL解码,以获取正确的文件名。

客户端可以通过调用DELETE方法请求来删除文件,例如/delete/{filename}

总结

Spring Cloud Alibaba框架提供了简单易用的OSS对象存储解决方案,使我们能够方便地进行文件的存储和管理。通过上述的演示,我们可以学会如何在Spring Cloud Alibaba中使用OSS对象存储。希望这篇博客能够帮助到你。如果你有任何问题或意见,欢迎留言讨论。

相似文章

    评论 (0)