Grails3文件上传到腾讯COS(OSS)

2018-11-30 00:54:39

build.gradle中引入依赖

  1. // 腾讯云oss
  2. compile ('com.qcloud:cos_api:5.4.9') {
  3. exclude group: 'org.slf4j', module: 'slf4j-log4j12'
  4. }

grails-app/conf下创建一个application-oss.yml文件

  1. oss:
  2. secretId: AKI**************************H7Ti
  3. secretKey: FN**************************Ns
  4. regionName: ap-chengdu
  5. bucket: img-555231231
  6. accessAddr: http://www.baidu.com # 访问地址

然后在application.yml中加入

  1. spring:
  2. profiles:
  3. include: oss

新建一个TencentConfigJavaBean

  • 可以直接在grails-app/utils下,也可以在src/main/java
  1. package first.blood.cn.tools.oss.tencent;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.context.annotation.Configuration;
  4. /**
  5. * 腾讯云oss初始化配置
  6. * @Author Lee
  7. * @Description
  8. * @Date 2018年11月18日 18:51
  9. */
  10. @Configuration
  11. @ConfigurationProperties(prefix = "oss")
  12. public class TencentConfig {
  13. private String secretId;
  14. private String secretKey;
  15. private String regionName;
  16. private String bucket;
  17. //访问时的域名
  18. private String accessAddr;
  19. public String getAccessAddr() {
  20. return accessAddr;
  21. }
  22. public void setAccessAddr(String accessAddr) {
  23. this.accessAddr = accessAddr;
  24. }
  25. public String getSecretId() {
  26. return secretId;
  27. }
  28. public void setSecretId(String secretId) {
  29. this.secretId = secretId;
  30. }
  31. public String getSecretKey() {
  32. return secretKey;
  33. }
  34. public void setSecretKey(String secretKey) {
  35. this.secretKey = secretKey;
  36. }
  37. public String getRegionName() {
  38. return regionName;
  39. }
  40. public void setRegionName(String regionName) {
  41. this.regionName = regionName;
  42. }
  43. public String getBucket() {
  44. return bucket;
  45. }
  46. public void setBucket(String bucket) {
  47. this.bucket = bucket;
  48. }
  49. }

接下来创建一个文件上传的配置类(工具类)TencentOss

  • 与前面的TencentConfig放在一个包下
  1. package first.blood.cn.tools.oss.tencent;
  2. import com.qcloud.cos.COSClient;
  3. import com.qcloud.cos.ClientConfig;
  4. import com.qcloud.cos.auth.BasicCOSCredentials;
  5. import com.qcloud.cos.auth.COSCredentials;
  6. import com.qcloud.cos.model.ObjectMetadata;
  7. import com.qcloud.cos.model.PutObjectResult;
  8. import com.qcloud.cos.region.Region;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Component;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. /**
  14. * @Author Lee
  15. * @Description
  16. * @Date 2018年11月18日 18:35
  17. */
  18. @Component
  19. public class TencentOss {
  20. @Autowired
  21. private TencentConfig tc;
  22. /**
  23. * 上传至腾讯云COS
  24. *
  25. * @param inputStream 输入流
  26. * @param fileName 保存路径+文件名:/2018/11/21/demo.png
  27. * @param contentType 文件类型,默认是 application/octet-stream
  28. * @return
  29. */
  30. public String upload(InputStream inputStream, String fileName) throws IOException {
  31. COSClient cosClient = null;
  32. try {
  33. // 1 初始化用户身份信息(secretId, secretKey)
  34. COSCredentials cred = new BasicCOSCredentials(tc.getSecretId(), tc.getSecretKey());
  35. // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
  36. // clientConfig中包含了设置region, https(默认http), 超时, 代理等set方法, 使用可参见源码或者接口文档FAQ中说明
  37. ClientConfig clientConfig = new ClientConfig(new Region(tc.getRegionName()));
  38. // 配置使用https
  39. // 3 生成cos客户端
  40. cosClient = new COSClient(cred, clientConfig);
  41. // bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
  42. String bucketName = tc.getBucket();
  43. ObjectMetadata objectMetadata = new ObjectMetadata();
  44. PutObjectResult putObjectResult = cosClient.putObject(bucketName, fileName, inputStream, objectMetadata);
  45. String etag = putObjectResult.getETag();
  46. } finally {
  47. if (inputStream != null) {
  48. inputStream.close();
  49. }
  50. if (cosClient != null) {
  51. cosClient.shutdown();
  52. }
  53. }
  54. return tc.getAccessAddr() + "/" + fileName;
  55. }
  56. }

然后在程序入口类上加上@ComponetScan注解

  1. package first.blood
  2. import grails.boot.GrailsApp
  3. import grails.boot.config.GrailsAutoConfiguration
  4. import org.springframework.context.annotation.ComponentScan
  5. @ComponentScan
  6. class Application extends GrailsAutoConfiguration {
  7. static void main(String[] args) {
  8. GrailsApp.run(Application, args)
  9. }
  10. }

控制器方法

  1. /**
  2. * 单文件上传
  3. * @return
  4. */
  5. def imgFile() {
  6. def map = [success: 0, message: "上传失败"]
  7. def file = null
  8. def inputStream = null
  9. try {
  10. file = params["editormd-image-file"]
  11. inputStream = file.getInputStream()
  12. String fileName = file.getOriginalFilename()
  13. if (!file && !fileName) {
  14. map.message = "请选择图片文件"
  15. render map as JSON
  16. return
  17. }
  18. // 判断文件大小,MAX_POST_SIZE自己定义
  19. if (file.getSize() > MAX_POST_SIZE) {
  20. map.message = "只能上传不超过2M的图片文件"
  21. render map as JSON
  22. return
  23. }
  24. // 判断是否是图片文件
  25. if (!ImgUtils.isImage(file.getInputStream())) {
  26. map.message = "只允许上传图片文件"
  27. render map as JSON
  28. return
  29. }
  30. String prefix = fileName.substring(fileName.lastIndexOf("."))
  31. // 新文件名,这里调用Date工具类生成目录结构2018/12/30
  32. String newFileName = DateUtils.getUrl() + "/" + UUIDUtils.id() + prefix
  33. String accessAddr = oss.upload(inputStream,newFileName)
  34. map.success = 1
  35. map.message = "上传成功"
  36. map.url = accessAddr
  37. } catch (e) {
  38. log.error("文件上传失败,msg={}", e)
  39. map.message = "请检查参数是否正确,只能上传不超过2M的图片文件"
  40. }
  41. render map as JSON
  42. }

踩坑注意事项

  • 文件流只能用一次
    • 前面定义了inputStream在中途用过一次就会出问题,上传的文件只有几B大小,有的是0B

0
0
0

添加评论

正在回复:
取消
0
0
0
0