java实现阿里云OSS上传下载

it2026-08-04  0

首先得开通OSS服务

话不多说,直接上代码先导入所需依赖 1,上传2,下载

注:我这里使用的accessKeyId,accessKeySecret等仅作为展示,实际参数查看开通的oss服务

话不多说,直接上代码

先导入所需依赖

<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.8.0</version> </dependency>

1,上传

/** * 上传音乐信息 * @param file * @return */ @Override @PostMapping("/upload/music") public BaseResult uploadmusic(@RequestPart MultipartFile file) throws Exception{ // 创建oss对象 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { if (ossClient.doesBucketExist(bucketName)) { System.out.println("您已经创建Bucket:" + bucketName + "。"); } else { System.out.println("您的Bucket不存在,创建Bucket:" + bucketName + "。"); ossClient.createBucket(bucketName); } // 要上传到的oss地址 String fileKey = "Music/" + file.getOriginalFilename(); // 上传 ossClient.putObject(bucketName, fileKey, file.getInputStream()); } catch (Exception e) { e.printStackTrace(); } finally { ossClient.shutdown(); } }

2,下载

package com.czxy.music.web.test.day01; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.GetObjectRequest; import java.io.File; /** * Created by zfwy on 2020/10/19. */ public class Myqxin01 { private static String endpoint = "oss-cn-beijing.aliyuncs.com"; private static String accessKeyId = "LTAI4sdfmyNAxS6GxmPLK1Y6"; private static String accessKeySecret = "jynYmysdfowdwLDsi9rA3QYuVBmVdO8T"; private static String bucketName = "jjzwcswfsy"; public static void main(String[] args) { // OSS存储文件的路径 String basePath = "img/1.jpg"; // 下载到本地的目录,自己随意存放 String localPath = "D:\\Music\\"; File file = new File(localPath); // 如果目录不存在,则创建目录 if (!file.exists()){ file.mkdirs(); } // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。 ossClient.getObject(new GetObjectRequest(bucketName, basePath), new File(localPath+"1.jpg")); // 这里的1.jpg是下载后的命名,可以更改 // 关闭OSSClient。 ossClient.shutdown(); } }
最新回复(0)