1 依赖包,对应版本号
<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.15.1</version></dependency>
2 配置文件
package com.jcl.magic.common.config;import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @Classname OssConfig* @Description TODO* @Date 2023/12/1 10:08* @Created by mingcai*/
@Configuration
//@PropertySource(value = {"classpath:application-oss.properties"})
@ConfigurationProperties(prefix = "aliyun")
@Data
public class OssConfig {private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;private String urlPrefix;@Beanpublic OSS oSSClient() {return new OSSClient(endpoint, new DefaultCredentialProvider(accessKeyId, accessKeySecret), new ClientConfiguration());}}
3 配置XML文件
aliyun:accessKeyId: LTxxxxxxxxaccessKeySecret: OfxxxxxxxxxxbucketName: zhyt-cmsendpoint: oss-hangzhou.aliyuncs.comurlPrefix: https://xxxx-oss-hangzhou.aliyuncs.com/
4 需要说明, 在阿里云服务配置界面, 需要把公共读权限放开,这样就可以直接使用完整路径地址直接下载文件
5 封装代码和数据表
package com.jcl.magic.service.impl;import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jcl.magic.common.config.OssConfig;
import com.jcl.magic.common.dto.FileUploadResult;
import com.jcl.magic.common.entity.SysFiles;
import com.jcl.magic.mapper.FilesMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;/*** 阿里云OSS 文件服务* @Classname FileUploadService* @Description TODO* @Date 2023/12/1 10:11* @Created by mingcai*/
@Service
public class FileUploadService {// 允许上传的格式private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png",".xml",".pdf",".docx",".txt"};@Autowiredprivate OSS ossClient;@Autowiredprivate OssConfig aliyunConfig;@Resourceprivate FilesMapper filesMapper;/*** 上传文件,直接使用地址下载,无法预览* @author lmc* @desc 文件上传 保存数据库*/public FileUploadResult uploadSave(MultipartFile uploadFile,String key,Long userId) {// 校验文件格式boolean isLegal = false;for (String type : IMAGE_TYPE) {if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {isLegal = true;break;}}//封装Result对象,并且将文件的byte数组放置到result对象中FileUploadResult fileUploadResult = new FileUploadResult();if (!isLegal) {fileUploadResult.setStatus("error");return fileUploadResult;}//文件新路径String fileName = uploadFile.getOriginalFilename();String filePath = getFilePath(fileName);// 上传到阿里云try {// 直接下载文件,预览XML或者HTML文件ObjectMetadata meta = new ObjectMetadata();meta.setContentType("text/html");ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(uploadFile.getBytes()),meta);//ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(uploadFile.getBytes()));} catch (Exception e) {e.printStackTrace();//上传失败fileUploadResult.setStatus("error");return fileUploadResult;}fileUploadResult.setStatus("done");fileUploadResult.setResponse("success");SysFiles file = new SysFiles();file.setUrl(this.aliyunConfig.getUrlPrefix() + filePath);file.setOriginalFileNames(uploadFile.getOriginalFilename());file.setName(key);file.setUserId(userId);filesMapper.insert(file);//this.aliyunConfig.getUrlPrefix() + filePath 文件路径需要保持数据库fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);fileUploadResult.setUid(file.getId());return fileUploadResult;}/*** @author lmc* @desc 文件上传*/public FileUploadResult upload(MultipartFile uploadFile) {// 校验图片格式boolean isLegal = false;for (String type : IMAGE_TYPE) {if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {isLegal = true;break;}}//封装Result对象,并且将文件的byte数组放置到result对象中FileUploadResult fileUploadResult = new FileUploadResult();if (!isLegal) {fileUploadResult.setStatus("error");return fileUploadResult;}//文件新路径String fileName = uploadFile.getOriginalFilename();String filePath = getFilePath(fileName);// 上传到阿里云try {ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(uploadFile.getBytes()));} catch (Exception e) {e.printStackTrace();//上传失败fileUploadResult.setStatus("error");return fileUploadResult;}fileUploadResult.setStatus("done");fileUploadResult.setResponse("success");//this.aliyunConfig.getUrlPrefix() + filePath 文件路径需要保持数据库fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);fileUploadResult.setUid(System.currentTimeMillis());return fileUploadResult;}/*** @author lmc* @desc 生成路径以及文件名 例如://images/2019/04/28/15564277465972939.jpg*/private String getFileImagesPath(String sourceFileName) {DateTime dateTime = new DateTime();return "images/" + dateTime.toString("yyyy") + "/" + dateTime.toString("MM") + "/" + dateTime.toString("dd") + "/" + System.currentTimeMillis() + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, ".");}private String getFilePath(String sourceFileName) {DateTime dateTime = new DateTime();return "drawline/" + dateTime.toString("yyyy") + "/" + dateTime.toString("MM") + "/" + dateTime.toString("dd") + "/" + System.currentTimeMillis() + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, ".");}/*** @author lmc* @desc 查看文件列表*/public List<OSSObjectSummary> list() {// 设置最大个数。final int maxKeys = 200;// 列举文件。ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(aliyunConfig.getBucketName()).withMaxKeys(maxKeys));List<OSSObjectSummary> sums = objectListing.getObjectSummaries();return sums;}/*** @author lmc* @desc 删除文件*/public FileUploadResult delete(String objectName) {ossClient.deleteObject(aliyunConfig.getBucketName(), objectName);FileUploadResult fileUploadResult = new FileUploadResult();fileUploadResult.setName(objectName);fileUploadResult.setStatus("removed");fileUploadResult.setResponse("success");return fileUploadResult;}/*** @author lmc* @desc 下载文件*/public InputStream exportOssFile(String objectName) {// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(), objectName);// 读取文件内容。InputStream is = ossObject.getObjectContent();return is;}/*** @author lmc* @desc 删除文件*/public FileUploadResult getFileUrl(String key) {if (StringUtils.isBlank(key)) {return new FileUploadResult();}SysFiles file = new SysFiles();file.setName(key);return getFileObj(file);}public FileUploadResult getFileObj(SysFiles file) {if (ObjectUtils.isEmpty(file)) {return new FileUploadResult();}FileUploadResult fileUploadResult = new FileUploadResult();LambdaQueryWrapper<SysFiles> queryWrapper = new LambdaQueryWrapper<>();if (StringUtils.isNotBlank(file.getName())) {queryWrapper.eq(true, SysFiles::getName, file.getName());}if (StringUtils.isNotBlank(file.getFileName())) {queryWrapper.eq(true, SysFiles::getFileName, file.getFileName());}if (null != file.getId()) {queryWrapper.eq(true, SysFiles::getId, file.getId());}queryWrapper.orderByDesc(SysFiles::getId);List<SysFiles> files = filesMapper.selectList(queryWrapper);if (!CollectionUtils.isEmpty(files)) {SysFiles sysFiles = files.get(0);fileUploadResult.setName(sysFiles.getUrl());}fileUploadResult.setResponse("success");return fileUploadResult;}}