QiniuOssServiceImplI.java 2.4 KB
Newer Older
zlt2000's avatar
zlt2000 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
package com.central.file.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.central.file.model.FileInfo;
import com.central.file.model.FileType;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

/**
 * 七牛云oss存储文件
zlt2000's avatar
zlt2000 已提交
21 22
 *
 * @author 作者 owen E-mail: 624191343@qq.com
zlt2000's avatar
zlt2000 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
 */
@Slf4j
@Service("qiniuOssServiceImpl")
public class QiniuOssServiceImplI extends AbstractIFileService implements InitializingBean {
    @Autowired
    private UploadManager uploadManager;
    @Autowired
    private BucketManager bucketManager;
    @Autowired
    private Auth auth;
    @Value("${qiniu.oss.bucketName:xxxxx}")
    private String bucket;
    @Value("${qiniu.oss.endpoint:xxxxx}")
    private String endpoint;
    private StringMap putPolicy;

    @Override
    protected FileType fileType() {
        return FileType.QINIU;
    }

    @Override
    protected void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception {
        // 调用put方法上传
        uploadManager.put(file.getBytes(), fileInfo.getName(), auth.uploadToken(bucket));
        fileInfo.setUrl(endpoint + "/" + fileInfo.getName());
        fileInfo.setPath(endpoint + "/" + fileInfo.getName());
    }

    @Override
    protected boolean deleteFile(FileInfo fileInfo) {
        try {
            Response response = bucketManager.delete(this.bucket, fileInfo.getPath());
            int retry = 0;
            while (response.needRetry() && retry++ < 3) {
                response = bucketManager.delete(bucket, fileInfo.getPath());
            }
        } catch (QiniuException e) {
            return false;
        }
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.putPolicy = new StringMap();
        putPolicy.put("returnBody",
                "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
    }
}