七牛云私有桶文件操作

package com.service;


import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.zy.webserver.common.Constant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;


@Service
public class FileService {
    @Value("${qiniu.accessKey}")
    private String accessKey;
    @Value("${qiniu.secretKey}")
    private String secretKey;
    @Value("${qiniu.bucket}")
    private String bucket;//桶
    @Value("${qiniu.baseUrl}")
    private String baseUrl;//域名
	/**
     * 上传到七牛云 
     * @param file
     * @return
     */
    public String uploadFile(MultipartFile file) {
        //构造一个带指定 Region 对象的配置类
        if (file.isEmpty()) {
            return "文件为空";
        }
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            String originalFilename = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            //默认不指定key的情况下,以文件内容的hash值作为文件名
            String key = originalFilename;
            Response response = uploadManager.put(bytes, key, upToken);
            if (response.statusCode != 200) {
                return "上传失败";
            }
            return baseUrl+"/"+key;
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
    }

    /**
     * 获取下载七牛云文件路径
     * @param baseUrl 域名+key
     * @return
     */
    public String downloadFile(String baseUrl) {
        Auth auth = Auth.create(accessKey, secretKey);
        String downloadUrl = auth.privateDownloadUrl(baseUrl);
        return downloadUrl;
    }

    /**
     * 删除七牛云文件
     * @param baseUrl
     * @return
     */
    public Boolean deleteFile(String fileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket,fileName);
        } catch (Exception ex) {
            //如果遇到异常,说明删除失败
            return false;
        }
        return true;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值