文件上传功能(阿里云OSS)

安装OSS Java SDK_对象存储(OSS)-阿里云帮助中心 (aliyun.com)

 

参照官方提供的SDK,改造一下,即可实现文件上传功能:

public class AliyunOSSTest {

   @Test
   public void testUploadFile() throws Exception {
       // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
       String endpoint = "https://oss-cn-beijing.aliyuncs.com";
       // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
       EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
       // 填写Bucket名称,例如examplebucket。
       String bucketName = "web2024";
       // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
       String objectName = "1.png";
       // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
       // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
       String filePath= "C:\\Users\\deng\\Pictures\\播仔0001.png";

       // 创建OSSClient实例。
       OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

       try {
           InputStream inputStream = new FileInputStream(filePath);
           // 创建PutObjectRequest对象。
           PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
           // 创建PutObject请求。
           PutObjectResult result = ossClient.putObject(putObjectRequest);
      } catch (OSSException oe) {
           System.out.println("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
           System.out.println("Error Message:" + oe.getErrorMessage());
           System.out.println("Error Code:" + oe.getErrorCode());
           System.out.println("Request ID:" + oe.getRequestId());
           System.out.println("Host ID:" + oe.getHostId());
      } catch (ClientException ce) {
           System.out.println("Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, such as not being able to access the network.");
           System.out.println("Error Message:" + ce.getMessage());
      } finally {
           if (ossClient != null) {
               ossClient.shutdown();
          }
      }
  }

}

在以上代码中,需要替换的内容为:

  • endpoint:阿里云OSS中的bucket对应的域名

  • bucketName:Bucket名称

  • objectName:对象名称,在Bucket中存储的对象的名称

  • filePath:文件路径

运行以上程序后,会把本地的文件上传到阿里云OSS服务器上。

 

案例

引入阿里云OSS上传文件工具类(由官方的示例代码改造而来)

/**
* 阿里云OSS操作工具类
*/
@Slf4j
public class AliyunOSSUtils {

   /**
    * 上传文件
    * @param endpoint endpoint域名
    * @param bucketName 存储空间的名字
    * @param content 内容字节数组
    */
   public static String upload(String endpoint, String bucketName, byte[] content, String extName) throws Exception {
       // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
       EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
       // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
       String objectName = UUID.randomUUID() + extName;

       // 创建OSSClient实例。
       OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
       try {
           // 创建PutObjectRequest对象。
           PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content));
           // 创建PutObject请求。
           PutObjectResult result = ossClient.putObject(putObjectRequest);
      } catch (OSSException oe) {
           log.error("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
           log.error("Error Message:" + oe.getErrorMessage());
           log.error("Error Code:" + oe.getErrorCode());
           log.error("Request ID:" + oe.getRequestId());
           log.error("Host ID:" + oe.getHostId());
      } catch (ClientException ce) {
           log.error("Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, such as not being able to access the network.");
           log.error("Error Message:" + ce.getMessage());
      } finally {
           if (ossClient != null) {
               ossClient.shutdown();
          }
      }

       return endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
  }

}

 修改UploadController代码:

@Slf4j
@RestController
public class UploadController {
   private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
   private String bucketName = "java417-web";

   @PostMapping("/upload")
   public Result upload(MultipartFile file) throws Exception {
       log.info("文件上传: {}", file.getOriginalFilename());
       String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
       String url = AliyunOSSUtils.upload(endpoint, bucketName, file.getBytes(), extName);
       return Result.success(url);
  }

}
@Data
@Configuration
@ConfigurationProperties(prefix = "oss")
public class AliyunOSSProperties {
/**
* 域名站点
*/
private String endpoint ;

/**
* 秘钥Id
*/
private String accessKeyId ;

/**
* 秘钥
*/
private String accessKeySecret ;

/**
* 桶名称
*/
private String bucketName ;
}
posted @   灵泽pro  阅读(42)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示