我正在使用 Java Client Library 将图像上传到云存储图像已上传到存储桶,但当我尝试访问它们时,浏览器中显示黑屏。因此,我深入研究了图像上传到云存储后的类型。
我将从云存储下载的图片上传到 Check File Type .com 它显示文件类型为数据,MIME/类型为application/octet-stream,而不是图像
所以,我从我的电脑上传了相同的原始图像,它完美地显示图像类型为image/jpeg
这是我使用 Java 客户端库编写的代码。
HTML Form to handle the upload
<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 code to Upload the Image
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);
为什么云存储无法正确检测图片类型?它对我想要显示相同图像的应用程序的其他部分产生不利影响。
更新
在同一对象的控制台中,Content-Type 显示为 image/jpeg
最佳答案
试试这个代码:
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上得到了以下结果:
关于java - 云存储 - 上传图像时文件的内容类型显示为数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53058801/