springboot+thymeleaf整合阿里云OOS对象存储图片的实现
短信预约 -IT技能 免费直播动态提醒
今天再进行创建项目时想使用阿里云oos进行存储图片 下面进行实操
1.先引入pom依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.9.1</version>
</dependency>
2.编写前端thymleeaf代码tetsfile.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
</style>
<body>
<img th:class="lazy" data-src="${url}" alt="" width="300px">
<form action="fileUpload" method="post" enctype="multipart/form-data">
<input type="file" name="fileName">
<input type="submit">
</form>
</body>
</html>
3.service层编写
下面的代码需要4个参数
package com.xuda.ntf.service;
import com.aliyun.oss.*;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.File;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
@Slf4j
public class AliyunOSSUtilService {
public static final String endpoint = "oss-cn-shanghai.aliyuncs.com";
public static final String accessKeyId = "LTA个人密钥";
public static final String accessKeySecret = "eF0UmiWp2回传密钥";
public static final String bucketName = "yygh-xuda回传name";
public static final String fileHost = "2022/cff"; //图片头部
private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
public String upload(File file) {
log.info("=========>OSS文件上传开始:" + file.getName());
// String fileHost=constantProperties.getFilehost();
System.out.println(endpoint + "endpoint");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = format.format(new Date());
if (null == file) {
return null;
}
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
try {
//容器不存在,就创建
if (!ossClient.doesBucketExist(bucketName)) {
ossClient.createBucket(bucketName);
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
ossClient.createBucket(createBucketRequest);
}
//创建文件路径
String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
//上传文件
PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
//设置权限 这里是公开读
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
if (null != result) {
log.info("==========>OSS文件上传成功,OSS地址:" + fileUrl);
return fileUrl;
}
} catch (OSSException oe) {
log.error(oe.getMessage());
} catch (ClientException ce) {
log.error(ce.getMessage());
} finally {
//关闭
ossClient.shutdown();
}
return null;
}
public List<OSSObjectSummary> getObjectList() {
OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
// 设置最大个数。
final int maxKeys = 200;
// 列举文件。
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
listObjectsRequest.setPrefix(fileHost + "/");
ObjectListing objectListing = ossClient.listObjects(listObjectsRequest.withMaxKeys(maxKeys));
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
return sums;
}
public String getUrl(String objectName ,long effectiveTime) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 设置URL过期时间
Date expiration = new Date(new Date().getTime() + effectiveTime);
GeneratePresignedUrlRequest generatePresignedUrlRequest ;
generatePresignedUrlRequest =new GeneratePresignedUrlRequest(bucketName, objectName);
generatePresignedUrlRequest.setExpiration(expiration);
URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
return url.toString();
}
public void delete(String objectName) {
try {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 删除文件。
ossClient.deleteObject(bucketName, objectName);
// 关闭OSSClient。
ossClient.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.controller层编写
写到代码中取
package com.xuda.ntf.controller;
import com.aliyun.oss.model.OSSObjectSummary;
import com.xuda.ntf.service.AliyunOSSUtilService;
import com.xuda.ntf.service.FileService;
import com.xuda.ntf.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Slf4j
@Controller
public class FileApiController {
String uploadUrl = "";
@Autowired
private AliyunOSSUtilService aliyunOSSUtil;
@RequestMapping("/getAllPic")
public String getAllPic(Model model){
// Hashtable hashtable = new Hashtable();
// 显示图片
ArrayList<String> listStr = new ArrayList<>();
List<OSSObjectSummary> list = aliyunOSSUtil.getObjectList();
String url = aliyunOSSUtil.getUrl(uploadUrl,5000);
model.addAttribute("fileNames",listStr);
model.addAttribute("url",url);
return "testfile.html";
}
@RequestMapping("/fileUpload")
public String upload(@RequestParam("fileName") MultipartFile file,Model model){
try {
if(null != file){
String filename = file.getOriginalFilename();
if(!"".equals(filename.trim())){
File newFile = new File(filename);
FileOutputStream os = new FileOutputStream(newFile);
os.write(file.getBytes());
os.close();
file.transferTo(newFile);
//上传到OSS
uploadUrl = aliyunOSSUtil.upload(newFile);
System.out.println(uploadUrl);
model.addAttribute("file",uploadUrl);
}
}
}catch (Exception ex){
ex.printStackTrace();
}
return "forward:getAllPic";
}
}
到此这篇关于springboot+thymeleaf整合阿里云OOS对象存储图片的实现的文章就介绍到这了,更多相关springboot+thymeleaf对象存储图片内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341