San*_*isy 0 java google-cloud-storage google-cloud-platform
使用 Java 库将对象上传到 GCP https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-code-sample并使用以下代码
public static void uploadObject(
String projectId, String bucketName, String objectName, String filePath) throws IOException {
Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
BlobId blobId = BlobId.of(bucketName, objectName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
storage.create(blobInfo, Files.readAllBytes(Paths.get(filePath)));
System.out.println(
"File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码运行良好,但是图像的内容类型是application/octet-stream
如何设置为image/jpg或image/png。如何在上传前设置元数据
BlobInfo有一个Builder有很多选项,包括setContentType。
如果您总是看到 builder/newBuilder,则需要进一步调查文档以查看是否还有其他(setter)。
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("image/jpeg").build();
Run Code Online (Sandbox Code Playgroud)
===已编辑===
public String determineContentType(File inputFile){
String contentType = // Your logic of determining type of file format
return contentType;
}
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType(determineContentType(yourFile)).build();
Run Code Online (Sandbox Code Playgroud)