java实现File文件上传到OSS
时间: 2023-11-29 15:04:19 浏览: 83
以下是Java实现File文件上传到OSS的示例代码:
```
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.File;
public class OSSFileUploader {
// 阿里云 OSS 信息
private static final String ENDPOINT = "your-endpoint";
private static final String ACCESS_KEY_ID = "your-access-key-id";
private static final String ACCESS_KEY_SECRET = "your-access-key-secret";
private static final String BUCKET_NAME = "your-bucket-name";
// 上传文件到 OSS
public static void uploadFile(File file) {
// 创建 OSS 客户端
OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
// 创建 PutObjectRequest 对象
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, file.getName(), file);
// 上传文件到 OSS
PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
// 打印上传结果
System.out.println("File uploaded: " + putObjectResult.getETag());
// 关闭 OSS 客户端
ossClient.shutdown();
}
public static void main(String[] args) {
// 上传本地文件
File file = new File("your-local-file-path");
uploadFile(file);
}
}
```
需要将上述代码中的 `your-endpoint`、`your-access-key-id`、`your-access-key-secret` 和 `your-bucket-name` 替换为自己的阿里云 OSS 相关信息,将 `your-local-file-path` 替换为要上传的本地文件路径。执行 `uploadFile()` 方法即可将本地文件上传到 OSS。
阅读全文