Spring boot 上传文件到腾讯云对象储存COS(完整步骤流程)
1.登录到腾讯云平台(https://cloud.tencent.com)
![](https://ask.qcloudimg.com/draft/3282482/4jpcnzsd10.png?imageView2/2/w/1620)
2.选择【云产品,对象存储】
![](https://ask.qcloudimg.com/draft/3282482/8gmhickqks.png?imageView2/2/w/1620)
3.新建
![](https://ask.qcloudimg.com/draft/3282482/bw3e1illmv.png?imageView2/2/w/1620)
![](https://ask.qcloudimg.com/draft/3282482/xkgkcye0k6.png?imageView2/2/w/1620)
![](https://ask.qcloudimg.com/draft/3282482/imecps6gca.png?imageView2/2/w/1620)
4.查看刚刚创建存
![](https://ask.qcloudimg.com/draft/3282482/xkgkcye0k6.png?imageView2/2/w/1620)
5.选择
![](https://ask.qcloudimg.com/draft/3282482/ggigubc3j9.png?imageView2/2/w/1620)
![](https://ask.qcloudimg.com/draft/3282482/8h14506smk.png?imageView2/2/w/1620)
6.创建Spring boot项目
<!--腾讯云存储依赖-->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.2.4</version>
</dependency>
7.把刚刚我们创建的腾讯云存储桶的信息添加进Spring boot项目的配置文件中
![](https://ask.qcloudimg.com/draft/3282482/s4sgbkakpw.png?imageView2/2/w/1620)
8.编写上传的控制器
package com.pingao.guns.modular.demo.controller;
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.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.UUID;
/**
* 文件上传控制器
*/
@Controlle
@RequestMapping(value = "/upload")
public class UploadController {
@Value("${spring.tengxun.accessKey}")
private String accessKey;
@Value("${spring.tengxun.secretKey}")
private String secretKey;
@Value("${spring.tengxun.bucket}")
private String bucket;
@Value("${spring.tengxun.bucketName}")
private String bucketName;
@Value("${spring.tengxun.path}")
private String path;
@Value("${spring.tengxun.qianzui}")
private String qianzui;
/**
* 上传道腾讯云服务器(https://cloud.tencent.com/document/product/436/10199)
* @return
*/
@RequestMapping(value = "/tengxun",method = RequestMethod.POST)
@ResponseBody
public Object Upload(@RequestParam(value = "file") MultipartFile file, HttpSession session){
if(file == null){
return new UploadMsg(0,"文件为空",null);
}
String oldFileName = file.getOriginalFilename();
String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
String newFileName = UUID.randomUUID()+eName;
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month=cal.get(Calendar.MONTH);
int day=cal.get