java实现oss文件上传
时间: 2023-11-18 21:50:15 浏览: 148
以下是java实现oss文件上传的示例代码:
```
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.FileInputStream;
import java.io.InputStream;
public class OSSUploadDemo {
public static void main(String[] args) {
String endpoint = "<yourEndpoint>";
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String bucketName = "<yourBucketName>";
String objectName = "<yourObjectName>";
String filePath = "<yourFilePath>";
// 创建OSSClient实例
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建上传请求
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new FileInputStream(filePath));
// 设置上传文件的元信息
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(putObjectRequest.getInputStream().available());
putObjectRequest.setMetadata(metadata);
// 执行上传操作并返回结果
PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
System.out.println("上传成功:" + putObjectResult.getETag());
} catch (Exception e) {
System.out.println("上传失败:" + e.getMessage());
} finally {
// 关闭OSSClient实例
ossClient.shutdown();
}
}
}
```
其中,需要替换的变量如下:
- `endpoint`:OSS服务的访问域名,例如`http://oss-cn-hangzhou.aliyuncs.com`
- `accessKeyId`:访问OSS服务的AccessKeyId
- `accessKeySecret`:访问OSS服务的AccessKeySecret
- `bucketName`:存储文件的Bucket名称
- `objectName`:上传文件在Bucket中的Object名称
- `filePath`:要上传的文件路径
阅读全文