首先,我们可以看移动云的API文档,下载他的开发包,导入我们的项目。
右击 文件 —》项目结构 —》库 —》点击右上角添加符号
导入我们下载的SDK依赖,然后去移动云官网快速入门把SDK复制下来
如下图所示
@ApiOperation("文件上传")
@PostMapping("/upload")
public RespBean upload(@RequestPart MultipartFile multipartFile) throws IOException {
String hostname = "域名"; // 域名
String accessKey = "AccessID"; // 秘钥ID
String secretKey = "AccessSecretKey"; // 秘钥值
String bucketName = "桶名称"; // 桶名称
String objectKey = "upload/"+multipartFile.getOriginalFilename(); // 设置指定路径
// multipartFile.getOriginalFilename() 文件名
// 创建 AmazonS3Client
ClientConfiguration opts = new ClientConfiguration();
opts.setSignerOverride("S3SignerType"); //单次上传
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3Client client = new AmazonS3Client(credentials, opts);
client.setEndpoint(hostname);
// 上传文件(Object)
byte[] content = multipartFile.getBytes();
// 解决文件文件只能下载不能查看问题
// ObjectMetadata objectMetadata = new ObjectMetadata();
//objectMetadata.setContentType(getcontentType(multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."))));
// objectMetadata 设置为空默认为每次打开都会下载文件
System.out.println(objectMetadata.getContentType());
client.putObject(bucketName, objectKey,
new ByteArrayInputStream(content), objectMetadata);
client.setObjectAcl(bucketName,objectKey, CannedAccessControlList.PublicRead);
// 关闭 client
client.shutdown();
// 访问路径 https://桶.域名/相对路径
return RespBean.success("成功",client.getResourceUrl(bucketName,objectKey));
}
解决图片上传之后访问只能下载不能预览问题
// 预览图片格式设置(解决图片上传之后访问只能下载不能预览问题)
public static String getcontentType(String FilenameExtension) {
if (FilenameExtension.equalsIgnoreCase(".bmp")) {
return "image/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(".xml")) {
return "text/xml";
}
return "image/jpg";
}
至此,我们集成移动云EOS就完成了