上传到谷歌云存储中的Android
问题描述:
使用Blob存储区API与HttpURLConnection的我有一个端点API方法,让我上传的网址,以谷歌云存储这样的:上传到谷歌云存储中的Android
@ApiMethod(name = "getUploadUrl", path = "get_upload_url", httpMethod = ApiMethod.HttpMethod.POST)
public CollectionResponse<String> getUploadUrl(@Named("objectName")String objectName){
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
String callbackUrl = "/handleupload";
String uploadUrl = blobstoreService.createUploadUrl(callbackUrl,
UploadOptions.Builder.withGoogleStorageBucketName("my-bucket"));
ArrayList<String> results = new ArrayList<>(1);
results.add(uploadUrl);
return CollectionResponse.<String>builder().setItems(results).build();
}
这成功返回一个网址给我要上传我的图像文件。
在Android中,我尝试将文件上传这样的:
private Boolean uploadImage(File file, String uploadUrl){
try {
long bytes = file.length();
URL url = new URL(uploadUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Content-Type", "image/jpg");
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
int bytesAvailable = 0;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
bytesAvailable = fileInputStream.available();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[ ] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0,bufferSize);
}
int responseCode = urlConnection.getResponseCode();
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
但我回来的400 Bad Request
响应。我认为我做错了什么。
我想用HttpURLConnection
类,因为Android的推荐过来HttpClient
(这是最让帖子有例子):http://android-developers.blogspot.com/2011/09/androids-http-clients.html
,我使用Blob存储区API来上传图片,而不是谷歌的Cloud Storage签名的URL,因为我可以通过回调服务器端来处理上传。
答
我从来没有尝试过自己,所以我不是100%确定。然而,公共documentation确实表明请求必须“包含文件上传字段,并且表单的enctype必须设置为multipart/form-data。” 有各种示例显示如何使用HttppUrlConnection发送此类请求 。 (这是一个example,但请确保您使用“文件”而不是“文件名”)。