在build.gradle
中引入依賴
compile ('com.qcloud:cos_api:5.4.9') {
exclude group: 'org.slf4j', module: 'slf4j-log4j12'
}
複製程式碼
在grails-app/conf
下建立一個application-oss.yml
檔案
oss:
secretId: AKI**************************H7Ti
secretKey: FN**************************Ns
regionName: ap-chengdu
bucket: img-555231231
accessAddr: http://www.baidu.com
複製程式碼
然後在application.yml
中加入
spring:
profiles:
include: oss
複製程式碼
新建一個TencentConfig
的JavaBean
類
- 可以直接在
grails-app/utils
下,也可以在src/main/java
下
package first.blood.cn.tools.oss.tencent;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "oss")
public class TencentConfig {
private String secretId;
private String secretKey;
private String regionName;
private String bucket;
private String accessAddr;
public String getAccessAddr() {
return accessAddr;
}
public void setAccessAddr(String accessAddr) {
this.accessAddr = accessAddr;
}
public String getSecretId() {
return secretId;
}
public void setSecretId(String secretId) {
this.secretId = secretId;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getRegionName() {
return regionName;
}
public void setRegionName(String regionName) {
this.regionName = regionName;
}
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
}
複製程式碼
接下來建立一個檔案上傳的配置類(工具類)TencentOss
package first.blood.cn.tools.oss.tencent;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
@Component
public class TencentOss {
@Autowired
private TencentConfig tc;
public String upload(InputStream inputStream, String fileName) throws IOException {
COSClient cosClient = null;
try {
COSCredentials cred = new BasicCOSCredentials(tc.getSecretId(), tc.getSecretKey());
ClientConfig clientConfig = new ClientConfig(new Region(tc.getRegionName()));
cosClient = new COSClient(cred, clientConfig);
String bucketName = tc.getBucket();
ObjectMetadata objectMetadata = new ObjectMetadata();
PutObjectResult putObjectResult = cosClient.putObject(bucketName, fileName, inputStream, objectMetadata);
String etag = putObjectResult.getETag();
} finally {
if (inputStream != null) {
inputStream.close();
}
if (cosClient != null) {
cosClient.shutdown();
}
}
return tc.getAccessAddr() + "/" + fileName;
}
}
複製程式碼
然後在程式入口類上加上@ComponetScan
註解
package first.blood
import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
import org.springframework.context.annotation.ComponentScan
@ComponentScan
class Application extends GrailsAutoConfiguration {
static void main(String[] args) {
GrailsApp.run(Application, args)
}
}
複製程式碼
控制器方法
def imgFile() {
def map = [success: 0, message: "上傳失敗"]
def file = null
def inputStream = null
try {
file = params["editormd-image-file"]
inputStream = file.getInputStream()
String fileName = file.getOriginalFilename()
if (!file && !fileName) {
map.message = "請選擇圖片檔案"
render map as JSON
return
}
if (file.getSize() > MAX_POST_SIZE) {
map.message = "只能上傳不超過2M的圖片檔案"
render map as JSON
return
}
if (!ImgUtils.isImage(file.getInputStream())) {
map.message = "只允許上傳圖片檔案"
render map as JSON
return
}
String prefix = fileName.substring(fileName.lastIndexOf("."))
String newFileName = DateUtils.getUrl() + "/" + UUIDUtils.id() + prefix
String accessAddr = oss.upload(inputStream,newFileName)
map.success = 1
map.message = "上傳成功"
map.url = accessAddr
} catch (e) {
log.error("檔案上傳失敗,msg={}", e)
map.message = "請檢查引數是否正確,只能上傳不超過2M的圖片檔案"
}
render map as JSON
}
複製程式碼
踩坑注意事項
- 檔案流只能用一次
- 前面定義了
inputStream
在中途用過一次就會出問題,上傳的檔案只有幾B大小,有的是0B