文件上传阿里云OSS
spring boot + mybatis-plus
pom.xml 导包
1 2 3 4 5 6 7 8 9 10 11 12 | <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version> 1.4 </version> </dependency> <!-- 阿里云 对象存储--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version> 3.15 . 0 </version> </dependency> |
.yml 配置
1 2 3 4 5 6 | servlet: multipart: max-request-size: 100MB mvc: pathmatch: matching-strategy: ant_path_matcher |
上传文件的工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | public class AliOssUtil { //存储空间所在的城市域名 public static final String endpoint = "oss-cn-beijing.aliyuncs.com" ; //账号的key -保密 public static final String accessKeyId = "LTAI5t5ZPUfK5nTEUPCwzSxP" ; //账号的密钥 -保密 public static final String accessKeySecret = "BdWzLO0B8Z7YhzBK3Hx2CvQJudyo32" ; //存储空间名 public static final String bucketName = "Java2022" ; //阿里云 Oss的客户端对象 private static OSS client; static { // 完成实例化 client = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret); } /** * @Description: 上传资源,新增文件 * @param: [fileName 上传的文件名, data 文件内容, date 访问地址的有效期] * @return: 返回 访问地址 */ public static String upload(String fileName, byte [] data, Date date){ // 上传文件内容 client.putObject(bucketName,fileName, new ByteArrayInputStream(data)); // 返回访问地址 return getUrl(fileName,date); } /** * @Description: 获取对象的访问地址 * @param: [fileName 文件名, date 访问地址的有效期] * @return: java.lang.String */ public static String getUrl(String fileName,Date date){ return client.generatePresignedUrl(bucketName,fileName,date).toString(); } /** * @Description: 验证对象是否存在 * @param: [fileName 文件名] * @return: boolean */ public static boolean exists(String fileName){ return client.doesObjectExist(bucketName,fileName); } /** * @Description: 删除文件 * @param: [fileName 文件名] * @return: boolean */ public static boolean delete(String fileName){ try { client.deleteObject(bucketName,fileName); return true ; } catch (Exception e){ return false ; } } } |
控制器写法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | @PostMapping ( "/uploadOss.do" ) public String uploadOss( @RequestPart MultipartFile file) throws IOException { // 验证文件是否为空 if (!file.isEmpty()){ // 获取文件名 String fn = file.getOriginalFilename(); // 获取文件内容 byte [] data = file.getBytes(); // 存储文件到阿里云的OSS服务器 Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, 10 ); String url = AliOssUtil.upload(fn, data, calendar.getTime()); return url; } else { return "文件为空!!!" ; } } |
本文作者:小※兽
本文链接:https://www.cnblogs.com/dsds/p/16667372.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步