vue+springboot上传excel到腾讯云存储

程序你得看得懂 2024-09-20 04:55:25
在一个Vue和Spring Boot项目中,将Excel文件上传到腾讯云对象存储(COS)需要几个步骤。以下是详细的实现步骤,包括前端Vue代码、后端Spring Boot代码,以及腾讯云COS的配置。 前端(Vue)首先,创建一个简单的上传表单。 后端(Spring Boot)1. 添加依赖在pom.xml中添加必要的依赖项,包括Spring Web和腾讯云COS SDK。 org.springframework.boot spring-boot-starter-web com.qcloud cos_api 5.6.31 2. 配置腾讯云COS在application.properties文件中添加腾讯云COS的配置信息。 tencent.cos.secret-id=YOUR_SECRET_ID tencent.cos.secret-key=YOUR_SECRET_KEY tencent.cos.region=YOUR_REGION tencent.cos.bucket-name=YOUR_BUCKET_NAME3. 创建上传控制器创建一个控制器来处理文件上传,并将文件存储到腾讯云COS。 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.region.Region; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; @RestController public FileUploadController { @Value("${tencent.cos.secret-id}") private String secretId; @Value("${tencent.cos.secret-key}") private String secretKey; @Value("${tencent.cos.region}") private String region; @Value("${tencent.cos.bucket-name}") private String bucketName; @PostMapping("/upload") public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return ResponseEntity.badRequest().body("File is empty"); } try { // Initialize COS client COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); ClientConfig clientConfig = new ClientConfig(new Region(region)); COSClient cosClient = new COSClient(cred, clientConfig); // Upload file to COS String key = file.getOriginalFilename(); PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file.getInputStream(), null); cosClient.putObject(putObjectRequest); // Close COS client cosClient.shutdown(); return ResponseEntity.ok("File uploaded successfully: " + key); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.status(500).body("Error uploading file: " + e.getMessage()); } } }腾讯云COS配置创建存储桶:登录腾讯云控制台,创建一个用于存储文件的存储桶。获取密钥:在腾讯云控制台的访问管理中,获取SecretId和SecretKey。设置权限:确保存储桶的权限设置允许你的应用进行文件上传操作。运行项目启动后端:运行Spring Boot应用。启动前端:运行Vue项目,确保前端能正确访问后端的上传接口。测试上传使用前端页面选择Excel文件并点击上传,检查腾讯云COS控制台确认文件已成功上传。
0 阅读:0

程序你得看得懂

简介:感谢大家的关注