我正在使用Java Client Library将图像上传到Cloud Storage,但是图像已上传到存储桶,但是当我尝试访问它们时,浏览器中会显示黑屏。因此,在将映像上传到Cloud Storage之后,我会对此进行检查以检查其类型。
我将从云存储下载的图像上传到 Check File Type .com ,它将文件类型显示为数据,将MIME / TYPE显示为 application / octet-stream ,而不是 image
因此,我从PC上传了同一张图片的原始图片,它完美地将图片类型显示为 image / jpeg
这是我使用Java客户端库编写的代码。
用于处理上载的HTML表单
<form action="/through" method="post" enctype="multipart/form-data">
<h3>Uploading File through App Engine instances to cloud storage</h3>
<label>Enter Your Team Name</label><br>
<input type="text" name="TeamName" ><br><br>
<label>Upload Team Logo</label><br>
<input type="file" name="teamLogo" required="required"><br><br>
<input type="submit" value="Upload Team Logo">
</form>
用于上传图片的Java代码
InputStream input = request.getInputStream();
ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
try {
int read = input.read();
while(read != -1) {
byteArrayStream.write(read);
read = input.read();
}
catch (IOException e){
//Handle Exception
}
byte[] fileBytes = byteArrayStream.toByteArray();
Storage storage = null;
try {
FileInputStream credentialsStream = new FileInputStream("JSONFile");
Credentials credentials = GoogleCredentials.fromStream(credentialsStream);
storage = StorageOptions.newBuilder().setCredentials(credentials).setProjectId("myProjectID").build().getService();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BlobId blobId = BlobId.of(BUCKET_NAME, USER_NAME+"TeamLogo.jpg");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("image/jpeg").build();
Blob blob = storage.create(blobInfo, fileBytes);
为什么Cloud Storage无法正确检测图像类型?它对我想显示相同图像的应用程序的其他部分产生不利影响。
更新
在控制台中,针对同一对象,内容类型显示为 image / jpeg
答案 0 :(得分:1)
尝试以下代码:
package com.example.storage;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import java.io.File;
import java.nio.file.Files;
public class QuickstartSample {
public static void main(String... args) throws Exception {
File fi = new File("source.jpg");
Storage storage = StorageOptions.getDefaultInstance().getService();
BlobId blobId = BlobId.of("your-bucket", "imagen.jpg");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("image/jpeg").build();
Blob blob = storage.create(blobInfo, Files.readAllBytes(fi.toPath()));
System.out.println(blob.getContentType());
}
}
我在CheckFileType上获得了以下结果:
答案 1 :(得分:0)
您可以指示客户端应用使用resumable upload将文件直接上传到Cloud Storage,而不是将文件上传到本地实例,然后再将其移动到Cloud Storage。
如果确实需要先将文件获取到本地实例(例如,在上传之前进行一些处理),则可以使用:
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = inStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();