使用Spring MVC保存文件是一种常见的需求,可以通过以下步骤实现:
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
return resolver;
}
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize("1024MB");
factory.setMaxRequestSize("1024MB");
return factory.createMultipartConfig();
}
@PostMapping("/upload")
public ResponseEntity<?> handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return new ResponseEntity<>("请上传文件", HttpStatus.BAD_REQUEST);
}
try {
// 保存文件到本地文件系统
Files.copy(file.getInputStream(), Paths.get(uploadPath + "/" + file.getOriginalFilename()));
return new ResponseEntity<>("文件上传成功", HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>("文件上传失败", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
首先,需要在pom.xml中添加腾讯云COS SDK的依赖:
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>1.0.0</version>
</dependency>
然后,可以使用以下代码将文件保存到腾讯云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.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
// 初始化COS客户端
COSCredentials cred = new BasicCOSCredentials("COS_SECRET_ID", "COS_SECRET_KEY");
ClientConfig clientConfig = new ClientConfig();
clientConfig.setRegion(new Region("COS_REGION"));
COSClient cosClient = new COSClient(cred, clientConfig);
// 上传文件到COS
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(file.getSize());
PutObjectRequest putObjectRequest = new PutObjectRequest("bucketName", "path/to/file", file.getInputStream(), objectMetadata);
cosClient.putObject(putObjectRequest);
// 关闭COS客户端
cosClient.shutdown();
总之,使用Spring MVC保存文件可以通过多种方式实现,包括保存到本地文件系统、腾讯云COS等。
领取专属 10元无门槛券
手把手带您无忧上云