springboot实现七牛云的文件上传下载

一:依赖包

		<dependency>
			<groupId>com.qiniu</groupId>
			<artifactId>qiniu-java-sdk</artifactId>
			<qiniu-java-sdk.version>7.7.0</qiniu-java-sdk.version>
		</dependency>

二:具体实现



@RestController
@RequestMapping("/sys/oss/qiniu")
public class OssController {
    @Autowired
    private OssQiNiuHelper ossQiNiuHelper;

    @Value("${jeecg.oss.qiniu.domain}")
    private String fileDomain;

    /**
     * 七牛云文件上传
     *
     * @param file 文件
     * @return
     */
    @PostMapping(value = "/upload")
    public Result<?> upload(MultipartFile file) {
        if (file == null) {
            return Result.error("上传文件不能为空");
        }
        try {
            FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));
            String yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            //默认不指定key的情况下,以文件内容的hash值作为文件名
            String fileKey = UUID.randomUUID().toString().substring(0,16).replace("-", "") + "-" + yyyyMMddHHmmss + fileExtend;
            Map<String, Object> map = new HashMap<>();
            DefaultPutRet uploadInfo = ossQiNiuHelper.upload(fileInputStream, fileKey);
            map.put("fileName", uploadInfo.key);
            map.put("name", originalFilename);
            map.put("size", file.getSize());
            //七牛云文件私有下载地址(看自己七牛云公开还是私有配置)
            map.put("url", "http://" + fileDomain + "/" + uploadInfo.key);
            return Result.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 七牛云私有文件下载
     *
     * @param filename 文件名
     * @return
     */
    @GetMapping(value = "/private/file/{filename}")
    public void privateDownload(@PathVariable("filename") String filename, HttpServletResponse response) {
        if (filename.isEmpty()) {
            return;
        }
        try {
            String privateFile = ossQiNiuHelper.getPrivateFile(filename);
            response.sendRedirect(privateFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 七牛云文件下载
     *
     * @param filename 文件名
     * @return
     */
    @RequestMapping(value = "/file/{filename}", method = {RequestMethod.GET})
    public void download(@PathVariable("filename") String filename, HttpServletResponse response) {
        if (filename.isEmpty()) {
            return;
        }
        try {
            String privateFile = ossQiNiuHelper.getFile(filename);
            response.sendRedirect("http://" + privateFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 七牛云文件下载
     *
     * @param filename 文件名
     * @return
     */
    @RequestMapping(value = "/file/delete/{filename}", method = {RequestMethod.GET})
    public Result<?> delete(@PathVariable("filename") String filename, HttpServletResponse response) {
        if (filename.isEmpty()) {
            return Result.error("文件不能为空");
        }
        try {
            boolean delete = ossQiNiuHelper.delete(filename);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok("文件删除成功");
    }
}

三:配置类



@Configuration
public class QiNiuConfig {
    @Value(value = "${jeecg.oss.qiniu.accessKey}")
    private String accessKey;
    @Value(value = "${jeecg.oss.qiniu.secretKey}")
    private String secretKey;
    @Value(value = "${jeecg.oss.qiniu.zone}")
    private String zone;

    /**
     * 初始化配置
     */
    @Bean
    public com.qiniu.storage.Configuration ossConfig() {
        System.out.println(zone);
        switch (zone) {
            case "huadong":
                return new com.qiniu.storage.Configuration(Region.huadong());
            case "huabei":
                return new com.qiniu.storage.Configuration(Region.huabei());
            case "huanan":
                return new com.qiniu.storage.Configuration(Region.huanan());
            case "beimei":
                return new com.qiniu.storage.Configuration(Region.beimei());
            default:
                throw new RuntimeException("存储区域配置错误");
        }
    }

    /**
     * 认证信息实例
     *
     * @return
     */
    @Bean
    public Auth auth() {
        return Auth.create(accessKey, secretKey);
    }

    /**
     * 构建一个七牛上传工具实例
     */
    @Bean
    public UploadManager uploadManager(com.qiniu.storage.Configuration configuration) {
        return new UploadManager(configuration);
    }

    /**
     * 构建七牛空间管理实例
     *
     * @param auth          认证信息
     * @param configuration com.qiniu.storage.Configuration
     * @return
     */
    @Bean
    public BucketManager bucketManager(Auth auth, com.qiniu.storage.Configuration configuration) {
        return new BucketManager(auth, configuration);
    }

    /**
     * Gson
     *
     * @return
     */
    @Bean
    public Gson gson() {
        return new Gson();
    }
}

@Component
public class OssQiNiuHelper {

    @Value("${jeecg.oss.qiniu.bucketName}")
    private String bucketName;
    @Value("${jeecg.oss.qiniu.domain}")
    private String fileDomain;

    @Autowired
    private Configuration configuration;
    @Autowired
    private UploadManager uploadManager;
    @Autowired
    private BucketManager bucketManager;


    // 密钥配置
    @Autowired
    private Auth auth;
    @Autowired
    private Gson gson;


    //简单上传模式的凭证
    public String getUpToken() {
        return auth.uploadToken(bucketName);
    }

    //覆盖上传模式的凭证
    public String getUpToken(String fileKey) {
        return auth.uploadToken(bucketName, fileKey);
    }

    /**
     * 上传二进制数据
     *
     * @param data
     * @param fileKey
     * @return
     * @throws IOException
     */
    public DefaultPutRet upload(byte[] data, String fileKey) throws IOException {
        Response res = uploadManager.put(data, fileKey, getUpToken(fileKey));
        // 解析上传成功的结果
        DefaultPutRet putRet = gson.fromJson(res.bodyString(), DefaultPutRet.class);
        System.out.println(putRet.key);
        System.out.println(putRet.hash);
        return putRet;
    }

    /**
     * 上传输入流
     *
     * @param inputStream
     * @param fileKey
     * @return
     * @throws IOException
     */
    public DefaultPutRet upload(InputStream inputStream, String fileKey) throws IOException {
        Response res = uploadManager.put(inputStream, fileKey, getUpToken(fileKey), null, null);
        // 解析上传成功的结果
        DefaultPutRet putRet = gson.fromJson(res.bodyString(), DefaultPutRet.class);
        System.out.println(putRet.key);
        System.out.println(putRet.hash);
        return putRet;

    }

    /**
     * 删除文件
     *
     * @param fileKey
     * @return
     * @throws QiniuException
     */
    public boolean delete(String fileKey) throws QiniuException {
        Response response = bucketManager.delete(bucketName, fileKey);
        return response.statusCode == 200 ? true : false;
    }

    /**
     * 获取公共空间文件
     *
     * @param fileKey
     * @return
     */
    public String getFile(String fileKey) throws Exception {
        String encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
        String url = String.format("%s/%s", fileDomain, encodedFileName);
        return url;
    }


    /**
     * 获取私有空间文件
     *
     * @param fileKey
     * @return
     */
    public String getPrivateFile(String fileKey) throws Exception {
        String encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
        String publicUrl = String.format("%s/%s", "http://" + fileDomain, encodedFileName);
        long expireInSeconds = 3600;//1小时,可以自定义链接过期时间
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        return finalUrl;
    }

}

四:注意点

4.1.域名备案

使用七牛云的使用必须得备案域名,并且做dns解析,才能用七牛云的加速域名,七牛云默认是有几种解析方式的这里推荐使用dns解析,还有一种文件解析是比较麻烦的不推荐

4.2配置七牛云域名,一般是使用二级域名即可

配置完了二级域名去对应的域名提供服务商解析下记录即可生效

相关推荐

  1. springboot实现文件下载

    2024-04-04 17:32:04       17 阅读
  2. SpringBoot 下载文件

    2024-04-04 17:32:04       39 阅读
  3. SpringBoot实战】基于阿里实现文件

    2024-04-04 17:32:04       38 阅读
  4. Spring Boot + Vue3 实现大视频

    2024-04-04 17:32:04       31 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-04 17:32:04       17 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-04 17:32:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-04 17:32:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-04 17:32:04       18 阅读

热门阅读

  1. Linux常见命令简介

    2024-04-04 17:32:04       15 阅读
  2. 探索Django REST框架构建强大的API

    2024-04-04 17:32:04       17 阅读
  3. redis-乐观锁Watch使用方法

    2024-04-04 17:32:04       19 阅读
  4. python用fastapi快速写一个增删改查的接口

    2024-04-04 17:32:04       15 阅读
  5. Linux内核调试之如何用kdb调试

    2024-04-04 17:32:04       16 阅读