--pom.xml加入阿里OSS存储依赖 <!--阿里云OSS存储--> <dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>2.8.3</version> </dependency>
--配置阿里云oss相关常量参数
/** @Author: xxxx @Description: ${description} 阿里云 constant @Date: 2020/11/26 14:15 */
public class AliyunOSSConfigConstant {// 私有构造方法 禁止该类初始化private AliyunOSSConfigConstant() {}// 仓库名称public static final String BUCKET_NAME ="your backetname";// 地域节点public static final String END_POINT ="your endpoint address";// AccessKey ID 阿里云AccessKeypublic static final String AccessKey_ID ="your accesskeyid";// Access Key Secret 阿里云Secretpublic static final String AccessKey_Secret ="your acesskeySecret";
}
--编写操作oss的工具类
/** @Author: xxxx @Description: ${description}阿里云OSS工具类 @Date: 2020/11/26 14:13 */
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import com.stdl.chargingpile.config.constant.Constants;
import com.stdl.chargingpile.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Random;public class AliyunOSSUtil {@Autowired private OrderService orderService2;String filedir="img/";private static final Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);/*** 删除一个Bucket和其中的Objects** @param client* @param bucketName* @throws OSSException* @throws ClientException*/public static void deleteBucket(OSSClient client, String bucketName)throws OSSException, ClientException {ObjectListing ObjectListing = client.listObjects(bucketName);List<OSSObjectSummary> listDeletes = ObjectListing.getObjectSummaries();for (int i = 0; i < listDeletes.size(); i++) {String objectName = listDeletes.get(i).getKey();// 如果不为空,先删除bucket下的文件client.deleteObject(bucketName, objectName);}client.deleteBucket(bucketName);}/*** 把Bucket设置为所有人可读** @param client* @param bucketName* @throws OSSException* @throws ClientException*/public static void setBucketPublicReadable(OSSClient client, String bucketName)throws OSSException, ClientException {// 创建bucketclient.createBucket(bucketName);// 设置bucket的访问权限,public-read-write权限client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);}/*** 上传文件** @param client* @param bucketName* @param key* @param filename* @param contentType default "image/gif"* @throws OSSException* @throws ClientException* @throws FileNotFoundException*/public static String uploadFile(OSSClient client, String bucketName, String key, String filename, String contentType)throws OSSException, ClientException, FileNotFoundException {File file = new File(filename);contentType = contentType == null ? "image/gif" : contentType;ObjectMetadata objectMeta = new ObjectMetadata();objectMeta.setContentLength(file.length());objectMeta.setContentType(contentType);InputStream input = new FileInputStream(file);PutObjectResult result = client.putObject(bucketName, key, input, objectMeta);return result.getETag();}/*** 下载文件** @param client* @param bucketName* @param key* @param filename* @throws OSSException* @throws ClientException*/public static void downloadFile(OSSClient client, String bucketName, String key, String filename)throws OSSException, ClientException {client.getObject(new GetObjectRequest(bucketName, key), new File(filename));}/*** 创建一个文件夹** @param client* @param bucketName* @param folderPah*/public static void createFolder(OSSClient client, String bucketName, String folderPah) {ObjectMetadata objectMeta = new ObjectMetadata();byte[] buffer = new byte[0];ByteArrayInputStream in = new ByteArrayInputStream(buffer);objectMeta.setContentLength(0);try {client.putObject(bucketName, folderPah, in, objectMeta);} catch (Exception e) {e.printStackTrace();} finally {try {in.close();} catch (IOException e) {e.printStackTrace();}}}/*** 删除一个OSS文件对象** @param client* @param bucketName* @param key*/public static void deleteObject(OSSClient client, String bucketName, String key) {client.deleteObject(bucketName, key);}public static String reFundPath(String mechNo){String certpath = TMP_DIR + File.separator + mechNo;boolean dirs = createDir(certpath);if(dirs==true){OSSClient client =new OSSClient(Constants.endpoint, accessKeyId, accessKeySecret);downloadFile(client,Constants.bucket,mechNo+"/apiclient_cert.p12",certpath + File.separator + "apiclient_cert.p12");}System.out.println(certpath + File.separator + "apiclient_cert.p12");return certpath;}/*** 获取系统临时目录*/private static final String TMP_DIR= System.getProperty("java.io.tmpdir");public static boolean createDir(String destDirName) {File dir = new File(destDirName);if (dir.exists()) {System.out.println("创建目录" + destDirName + "目标目录已经存在,无需重新创建");return true;}if (!destDirName.endsWith(File.separator)) {destDirName = destDirName + File.separator;}// 创建目录if (dir.mkdirs()) {System.out.println("创建目录" + destDirName + "成功!");return true;} else {System.out.println("创建目录" + destDirName + "失败!");return false;}}/**** 上传图片* @param file* @return*/public String uploadImg2Oss(MultipartFile file) {if (file.getSize() > 1024 * 1024 *20) {return "图片太大";//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_TOO_MAX);}String originalFilename = file.getOriginalFilename();String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();Random random = new Random();String name = random.nextInt(10000) + System.currentTimeMillis() + substring;try {InputStream inputStream = file.getInputStream();this.uploadFile2OSS(inputStream, name);return name;//RestResultGenerator.createSuccessResult(name);} catch (Exception e) {return "上传失败";//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_UPLOAD);}}/*** 上传图片获取fileUrl* @param instream* @param fileName* @return*/private String uploadFile2OSS(InputStream instream, String fileName) {String ret = "";try {//创建上传Object的MetadataObjectMetadata objectMetadata = new ObjectMetadata();objectMetadata.setContentLength(instream.available());objectMetadata.setCacheControl("no-cache");objectMetadata.setHeader("Pragma", "no-cache");objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));objectMetadata.setContentDisposition("inline;filename=" + fileName);//上传文件OSSClient ossClient = new OSSClient(Constants.endpoint, accessKeyId, accessKeySecret);PutObjectResult putResult = ossClient.putObject(bucket, filedir + fileName, instream, objectMetadata);ret = putResult.getETag();} catch (IOException e) {logger.error(e.getMessage(), e);} finally {try {if (instream != null) {instream.close();}} catch (IOException e) {e.printStackTrace();}}return ret;}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";}/*** 获取图片路径* @param fileUrl* @return*/public String getImgUrl(String fileUrl) {if (!StringUtils.isEmpty(fileUrl)) {String[] split = fileUrl.split("/");String url = this.getUrl(this.filedir + split[split.length - 1]);return url;}return null;}/*** 获得url链接** @param key* @return*/public String getUrl(String key) {// 设置URL过期时间为10年 3600l* 1000*24*365*10Date expiration = new Date(new Date().getTime() + 3600L * 1000 * 24 * 365 * 10);// 生成URLOSSClient ossClient = new OSSClient(Constants.endpoint, accessKeyId, accessKeySecret);URL url = ossClient.generatePresignedUrl(bucket, key, expiration);if (url != null) {return url.toString();}return null;}/*** 多图片上传* @param fileList* @return*/public String checkList(List<MultipartFile> fileList) {String fileUrl = "";String str = "";String photoUrl = "";for(int i = 0;i< fileList.size();i++){fileUrl = uploadImg2Oss(fileList.get(i));str = getImgUrl(fileUrl);if(i == 0){photoUrl = str;}else {photoUrl += "," + str;}}return photoUrl.trim();}/*** 单个图片上传* @param file* @return*/public String checkImage(MultipartFile file){String fileUrl = uploadImg2Oss(file);String str = getImgUrl(fileUrl);return str.trim();}
}
以上就是操作阿里OSS的相关方法,供大家学习参考交流~!