页面展示
1、封装文件上传oos工具类
代码:
package com.yy.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.smart.apiresponsex.exception.BizException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.yy.dto.FileInfoDto;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Data
@Component
//@AllArgsConstructor
//固定代码,CV直接使用
public class AliOssUtil {
@Value("${aliyun.oss.bucketName}")
private String bucketName;
@Value("${aliyun.oss.endpoint}")
private String endpoint;
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.accessKeySecret}")
private String accessKeySecret;
@Value("${aliyun.oss.policy}")
private String policy;
/**
* 文件上传
*
* @param bytes :传入的文件要转为byte[]
* @param newName :表示在oss中存储的文件名字。
*/
private static Map<String,List<String>> fileMap = new HashMap<>();
static {
fileMap.put("imgs", CollUtil.newArrayList("jpg","png","jpeg","gif","bmp","webp","tif","tiff","psd","svg","ai","eps","ico","jfif","jpe","jif","jfif","jpe","jif","jfif","jpe","jif","jfif","jpe","jif","jfif","jpe","jif","jfif","jpe"));
fileMap.put("docs", CollUtil.newArrayList("doc","docx","xls","xlsx","ppt","pptx","pdf","txt","md","html","htm","css","js","json","xml","yml","yaml","java","c","cpp","h","hpp","hxx","hxx","h++","h++","hpp","hxx","h++","hxx","h++","hxx","h++"));
fileMap.put("music", CollUtil.newArrayList("mp3","wav","wma","flac" ));
fileMap.put("video", CollUtil.newArrayList("mp4","avi","rmvb","flv","wmv","mov","mkv","mpg","mpeg","3gp","rm","asf","asx","dat","vob","ts","m4v","m4a","m4p","m4b"));
}
public String upload1(byte[] bytes,String newName) {
OSS ossClient = new OSSClientBuilder().build(this.endpoint, this.accessKeyId, this.accessKeySecret);
String ext = StrUtil.subAfter(newName, ".", true);
String subPath = "default/";
for (Map.Entry<String, List<String>> entry : fileMap.entrySet()) {
if(entry.getValue().contains(ext.toLowerCase())){
subPath = entry.getKey();
}
}
String objectName = subPath + "/" + newName; // 构造带有目录的对象名
try {
// 创建PutObject请求。
ossClient.putObject(this.bucketName, objectName, new ByteArrayInputStream(bytes));
} catch (Exception oe) {
oe.printStackTrace();
throw new BizException(430,"文件上传失败");
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
//文件访问路径规则 https://BucketName.Endpoint/ObjectName
StringBuilder stringBuilder = new StringBuilder("https://");
stringBuilder
.append(bucketName)
.append(".")
.append(endpoint)
.append("/")
.append(objectName);
return stringBuilder.toString();
}
//查看oss
public List<FileInfoDto> list() {
OSS ossClient = new OSSClientBuilder().build(this.endpoint, this.accessKeyId, this.accessKeySecret);
//读取的最大数量
final int maxKeys = 200;
ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMaxKeys(maxKeys));
List<OSSObjectSummary> summaries = objectListing.getObjectSummaries();
// 使用Map来存储已经遇到的文件夹
Map<String, FileInfoDto> folderMap = new HashMap<>();
for (OSSObjectSummary summary : summaries) {
//文件夹名称和照片名
String key = summary.getKey();
String[] parts = key.split("/");
//文件夹名称
String folderName = parts.length > 1 ? parts[0] : "default";
//文件名
String fileName = parts[parts.length - 1];
// 检查文件夹是否已经存在于Map中
FileInfoDto fileInfo = folderMap.get(folderName);
if (fileInfo == null) {
// 如果文件夹不存在,创建一个新的FileInfoDto对象
fileInfo = new FileInfoDto();
fileInfo.setName(folderName);
fileInfo.setFileInfos(new ArrayList<>());
folderMap.put(folderName, fileInfo);
}
// 创建FileInfo对象并添加到FileInfoDto的fileInfos列表中
FileInfoDto.FileInfo fileInfo1 = new FileInfoDto.FileInfo();
fileInfo1.setName(fileName);
fileInfo1.setUrl(this.policy + key);
fileInfo.getFileInfos().add(fileInfo1);
}
// 从Map中收集所有的FileInfoDto对象
return new ArrayList<>(folderMap.values());
}
}
在配置文件中配置相应的信息
前端和之前分文件夹万能上传一样
后端controller代码
(1)图片上传
//上传到aliyun的代码
@PostMapping
//万能上传
public String upload(@RequestBody UploadDto uploadDto){
String name = uploadDto.getName();
String base64 = uploadDto.getBase64();
String[] base64Array = StrUtil.splitToArray(base64, "base64,");
byte[] bytes = Base64.decode(base64Array[1]);
name = PinyinUtil.getPinyin(name, "");
String newName = System.currentTimeMillis() +"_"+name;
// return aliOssUtil.upload1(bytes, newName);
return aliOssUtil.upload1(bytes, newName);
}
(2)获取图片集合
//aliyun图库查询图片的代码
@GetMapping
public List<FileInfoDto> selectTuku(){
return aliOssUtil.list();
}
因为访问文件的url是用桶的域名加上文件夹名称,加上文件夹名图片名,所以 在桶的域名前要加上https://,后面加一个/