1. 依赖
<!--腾讯云cos依赖-->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.54</version>
</dependency>
2. FileController
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
@Slf4j
@Api(value = "文件", tags = {"文件"})
@RestController
@RequestMapping("/file/upload")
public class FileController {
@Autowired
private COSUtils cosUtils;
@ApiOperation("文件上传")
@PostMapping
public AjaxResult upload(@RequestPart("file") MultipartFile file){
try {
String url = "";
// 获取后缀名
String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
// 最后上传生成的文件名
String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + fileSuffix;
// oss中的文件夹名
String objectName = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + finalFileName;
// 上传oss
cosUtils.uploadFileCOS(file.getInputStream(), objectName);
//获取文件的URl地址
url = cosUtils.getUrl(objectName);
log.info("url: {}",url);
AjaxResult ajax = AjaxResult.success();
ajax.put("url", url);
ajax.put("fileName", file.getOriginalFilename());
ajax.put("newFileName", FileUtils.getName(finalFileName));
return ajax;
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
}
3. AjaxResult
import java.util.HashMap;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.StringUtils;
/**
* 操作消息提醒
*
*/
public class AjaxResult extends HashMap<String, Object>
{
private static final long serialVersionUID = 1L;
/** 状态码 */
public static final String CODE_TAG = "code";
/** 返回内容 */
public static final String MSG_TAG = "msg";
/** 数据对象 */
public static final String DATA_TAG = "data";
/**
* 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
*/
public AjaxResult()
{
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
*/
public AjaxResult(int code, String msg)
{
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
* @param data 数据对象
*/
public AjaxResult(int code, String msg, Object data)
{
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
if (StringUtils.isNotNull(data))
{
super.put(DATA_TAG, data);
}
}
/**
* 返回成功消息
*
* @return 成功消息
*/
public static AjaxResult success()
{
return AjaxResult.success("操作成功");
}
/**
* 返回成功数据
*
* @return 成功消息
*/
public static AjaxResult success(Object data)
{
return AjaxResult.success("操作成功", data);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @return 成功消息
*/
public static AjaxResult success(String msg)
{
return AjaxResult.success(msg, null);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 成功消息
*/
public static AjaxResult success(String msg, Object data)
{
return new AjaxResult(HttpStatus.SUCCESS, msg, data);
}
/**
* 返回错误消息
*
* @return
*/
public static AjaxResult error()
{
return AjaxResult.error("操作失败");
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult error(String msg)
{
return AjaxResult.error(msg, null);
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 警告消息
*/
public static AjaxResult error(String msg, Object data)
{
return new AjaxResult(HttpStatus.ERROR, msg, data);
}
/**
* 返回错误消息
*
* @param code 状态码
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult error(int code, String msg)
{
return new AjaxResult(code, msg, null);
}
/**
* 方便链式调用
*
* @param key 键
* @param value 值
* @return 数据对象
*/
@Override
public AjaxResult put(String key, Object value)
{
super.put(key, value);
return this;
}
}
4. COSUtils
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.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.GeneratePresignedUrlRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
@Slf4j
@Component
public class COSUtils {
// API密钥
private static final String secretId = "xxxxxx";
private static final String secretKey = "xxxxxx";
// 桶名称
private static final String bucketName = "xxxxxx";
// 地域
private static final String region = "xxxxxx";
// 文件夹
private static final String FOLDER = "image/";
public static COSClient getCOSClient() {
// 1 初始化用户身份信息(secretId, secretKey)。
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 此处设置的地域为香港
Region rg = new Region(region);
ClientConfig clientConfig = new ClientConfig(rg);
// 这里建议设置使用 https 协议
// 从 5.6.54 版本开始,默认使用了 https
clientConfig.setHttpProtocol(HttpProtocol.https);
// 3 生成 cos 客户端。
COSClient cosClient = new COSClient(cred, clientConfig);
return cosClient;
}
public String uploadFileCOS(InputStream instream, String fileName){
String ret = "";
try {
// 创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(instream.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
objectMetadata.setHeader("Pragma", "no-cache");
// 上传文件
PutObjectResult putResult = getCOSClient().putObject(bucketName, FOLDER + fileName, instream, objectMetadata);
ret = putResult.getETag();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (instream != null) {
instream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
public static final String getContentType(String filenameExtension) {
if (filenameExtension.equalsIgnoreCase(".bmp")) {
return "application/x-bmp";
}
if (filenameExtension.equalsIgnoreCase(".gif")) {
return "image/gif";
}
if (filenameExtension.equalsIgnoreCase(".jpeg") ||
filenameExtension.equalsIgnoreCase(".jpg") ||
filenameExtension.equalsIgnoreCase(".png")) {
return "image/jpg";
}
if (filenameExtension.equalsIgnoreCase(".html")) {
return "text/html";
}
if (filenameExtension.equalsIgnoreCase(".txt")) {
return "text/plain";
}
if (filenameExtension.equalsIgnoreCase(".vsd")) {
return "application/vnd.visio";
}
if (filenameExtension.equalsIgnoreCase(".pptx") ||
filenameExtension.equalsIgnoreCase(".ppt")) {
return "application/vnd.ms-powerpoint";
}
if (filenameExtension.equalsIgnoreCase(".docx") ||
filenameExtension.equalsIgnoreCase(".doc")) {
return "application/msword";
}
if (filenameExtension.equalsIgnoreCase(".xla") ||
filenameExtension.equalsIgnoreCase(".xlc") ||
filenameExtension.equalsIgnoreCase(".xlm") ||
filenameExtension.equalsIgnoreCase(".xls") ||
filenameExtension.equalsIgnoreCase(".xlt") ||
filenameExtension.equalsIgnoreCase(".xlw")) {
return "application/vnd.ms-excel";
}
if (filenameExtension.equalsIgnoreCase(".xlsx")) {
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
if (filenameExtension.equalsIgnoreCase(".xml")) {
return "text/xml";
}
if (filenameExtension.equalsIgnoreCase(".pdf")) {
return "application/pdf";
}
if (filenameExtension.equalsIgnoreCase(".zip")) {
return "application/zip";
}
if (filenameExtension.equalsIgnoreCase(".tar")) {
return "application/x-tar";
}
if (filenameExtension.equalsIgnoreCase(".avi")) {
return "video/avi";
}
if (filenameExtension.equalsIgnoreCase(".mp4")) {
return "video/mpeg4";
}
if (filenameExtension.equalsIgnoreCase(".mp3")) {
return "audio/mp3";
}
if (filenameExtension.equalsIgnoreCase(".mp2")) {
return "audio/mp2";
}
// 默认下载
// return "application/octet-stream";
return "image/jpg";
}
public String getUrl(String key) {
GeneratePresignedUrlRequest req =
new GeneratePresignedUrlRequest(bucketName, key, HttpMethodName.GET);
// 设置签名过期时间(可选), 若未进行设置, 则默认使用 ClientConfig 中的签名过期时间(1小时)
// 10年
Date expirationDate = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
req.setExpiration(expirationDate);
COSClient cosClient = getCOSClient();
URL url = cosClient.generatePresignedUrl(req);
cosClient.shutdown();
if (url != null) {
return "https://" + url.getHost() + "/image" + url.getPath();
}
return "";
}
}
5. 上传成功