SpringBoot+ES项目:10.房源图片上传功能(七牛云)

1. 七牛云Java说明文档

https://developer.qiniu.com/kodo/sdk/java
资费说明
https://developer.qiniu.com/af/kb/1361/about-seven-niuyun-stored-billing-and-billing-instructions
2. 添加七牛云maven依赖

        
        
            com.qiniu
            qiniu-java-sdk
            [7.2.0, 7.2.99]
        

3. WebFileUpLoadConfig中配置七牛云

application.properties增加七牛key方便Config中调用

# qiniu 注意替换成自己申请的配置
qiniu.AccessKey=24b1Akz5a21LTyLAAwWj1VSRWj666sEVHwExPE4v
qiniu.SecretKey=O2ljrNnJr3Pcd0o3lxx1ugCT-dp5glvOB7mzQ_UH
qiniu.Bucket=smarticle
qiniu.cdn.prefix=http://pwbwge6b5.bkt.clouddn.com/

WebFileUpLoadConfig中增加七牛相关方法

    /**
     * 华东机房
     */
    @Bean
    public com.qiniu.storage.Configuration qiniuConfig() {
        return new com.qiniu.storage.Configuration(Zone.zone0());
    }


    /**
     * 构建一个七牛上传工具实例
     */
    @Bean
    public UploadManager uploadManager() {
        return new UploadManager(qiniuConfig());
    }

    @Value("${qiniu.AccessKey}")
    private String accessKey;
    @Value("${qiniu.SecretKey}")
    private String secretKey;

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

    /**
     * 构建七牛空间管理实例
     */
    @Bean
    public BucketManager bucketManager() {
        return new BucketManager(auth(), qiniuConfig());
    }

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

4. Service类创建

IQiNiuService 接口

package com.xunwu.service.house;

/**
 * 七牛云服务
 */
public interface IQiNiuService {
    com.qiniu.http.Response uploadFile(File file) throws QiniuException;

    com.qiniu.http.Response uploadFile(InputStream inputStream) throws QiniuException;

    com.qiniu.http.Response delete(String key) throws QiniuException;
}

实现服务类IQiNiuServiceImpl

package com.xunwu.service.house;
@service
public class IQiNiuServiceImpl implements IQiNiuService, InitializingBean {
    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private BucketManager bucketManager;

    @Autowired
    private Auth auth;

    @Value("${qiniu.Bucket}")
    private String bucket;

    private StringMap putPolicy;

    @Override
    public Response uploadFile(File file) throws QiniuException {
        Response response = this.uploadManager.put(file, null, getUploadToken());
        int retry = 0;
        while (response.needRetry() && retry < 3) {
            response = this.uploadManager.put(file, null, getUploadToken());
            retry++;
        }
        return response;
    }

    @Override
    public Response uploadFile(InputStream inputStream) throws QiniuException {
        Response response = this.uploadManager.put(inputStream, null, getUploadToken(), null, null);
        int retry = 0;
        //设置上传失败最多重试3次
        while (response.needRetry() && retry < 3) {
            response = this.uploadManager.put(inputStream, null, getUploadToken(), null, null);
            retry++;
        }
        return response;
    }

    @Override
    public Response delete(String key) throws QiniuException {
        Response response = bucketManager.delete(this.bucket, key);
        int retry = 0;
        while (response.needRetry() && retry++ < 3) {
            response = bucketManager.delete(bucket, key);
        }
        return response;
    }
	//定义返回结果值空间名高度宽度
    @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}}");
    }

    /**
     * 获取上传凭证
     * @return
     */
    private String getUploadToken() {
        return this.auth.uploadToken(bucket, null, 3600, putPolicy);
    }
}


5. 七牛云单元测试

package com.xunwu.house;

public class QiNiuServiceTests extends ApplicationTests {
    @Autowired
    private IQiNiuService qiNiuService;

    @Test
    public void testUploadFile() {
        String fileName = "E:\\tmp\\1.png";
        File file = new File(fileName);

        Assert.assertTrue(file.exists());

        try {
            Response response = qiNiuService.uploadFile(file);
            Assert.assertTrue(response.isOK());
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testDelete() {
        String key = "FvyNceBAaZF6TBh6OZpcEKlhuACG";
        try {
            Response response = qiNiuService.delete(key);
            Assert.assertTrue(response.isOK());
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }
}

6.结果
SpringBoot+ES项目:10.房源图片上传功能(七牛云)_第1张图片
SpringBoot+ES项目:10.房源图片上传功能(七牛云)_第2张图片

7. dto类

在web下建立dto包新建QiNiuPutRet类存储七牛云信息

package com.xunwu.web.dto;

public final class QiNiuPutRet {
    public String key;
    public String hash;
    public String bucket;
    public int width;
    public int height;

    @Override
    public String toString() {
        return "QiNiuPutRet{" +
                "key='" + key + '\'' +
                ", hash='" + hash + '\'' +
                ", bucket='" + bucket + '\'' +
                ", width=" + width +
                ", height=" + height +
                '}';
    }
}

8. Controller支持七牛云

adminController重写上传图片接口


	@Autowired
    private IQiNiuService qiNiuService;
    @Autowired
    private Gson gson;
    /**
     * 上传图片接口
     * @param file
     * @return
     */
    @PostMapping(value = "admin/upload/photo", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public ApiResponse uploadPhoto(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ApiResponse.ofStatus(ApiResponse.Status.NOT_VALID_PARAM);
        }

        String fileName = file.getOriginalFilename();

        try {
            InputStream inputStream = file.getInputStream();
            Response response = qiNiuService.uploadFile(inputStream);
            if (response.isOK()) {
                QiNiuPutRet ret = gson.fromJson(response.bodyString(), QiNiuPutRet.class);
                return ApiResponse.ofSuccess(ret);
            } else {
                return ApiResponse.ofMessage(response.statusCode, response.getInfo());
            }

        } catch (QiniuException e) {
            Response response = e.response;
            try {
                return ApiResponse.ofMessage(response.statusCode, response.bodyString());
            } catch (QiniuException e1) {
                e1.printStackTrace();
                return ApiResponse.ofStatus(ApiResponse.Status.INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            return ApiResponse.ofStatus(ApiResponse.Status.INTERNAL_SERVER_ERROR);
        }
    }

9. 结果
SpringBoot+ES项目:10.房源图片上传功能(七牛云)_第3张图片

SpringBoot+ES项目:10.房源图片上传功能(七牛云)_第4张图片

你可能感兴趣的:(Spring)