在java当中将InputStream流上传到minio服务器上面,并得到存储的路径
时间: 2024-10-08 16:23:18 浏览: 50
Java实现inputstream流的复制代码实例
在Java中,将`InputStream`上传到MinIO服务器通常涉及到`MultipartEntity`和`HttpClient`库的使用。下面是一个基本的例子:
首先,你需要创建一个`MultipartEntityBuilder`来构建多部分请求:
```java
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.InputStreamBody;
InputStream in = ...; // 输入流,比如文件的输入流
String bucketName = ...; // MinIO的bucket名称
String objectName = ...; // 存储的对象(文件)名字
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create()
.addPart("file", new InputStreamBody(in, "application/octet-stream"), "filename.ext") // 将文件流作为二进制内容添加
.setCharSet("UTF-8"); // 设置编码,这里为了兼容非英文字符
// 构建POST请求
HttpPost post = new HttpPost("https://" + minioServerUrl + "/buckets/" + bucketName + "/" + objectName);
post.setHeader("Authorization", "Bearer your-minio-access-key"); // 使用合适的Access Key进行身份验证
post.setHeader("Content-Type", entityBuilder.getContentType().getValue()); // 设置Content-Type
post.setEntity(entityBuilder.build());
```
然后你可以使用`HttpClient`发送POST请求并获取存储的路径。通常,存储的路径会在HTTP响应的头信息中,如`Location`字段:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { // 确保上传成功
Header locationHeader = response.getFirstHeader("Location");
if (locationHeader != null) {
String objectUrl = locationHeader.getValue();
// 这里就是存储的路径,例如:s3://your-bucket/filename.ext
System.out.println("File uploaded at: " + objectUrl);
}
} else {
// 处理错误
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
httpClient.close();
}
```
记得替换`minioServerUrl`, `your-minio-access-key`等为你实际的MinIO服务地址和Access Key。
阅读全文