Java 移动后端启动程序-上载到AppEngine Blobstore
如何使用Mobile Backend Starter或Google Cloud Endpoints将文件从Android上传到Google App Engine Blobstore?与Mobile Backend Starter共享我的到期日 要获取上传和下载URL,您需要将这两个方法添加到Java 移动后端启动程序-上载到AppEngine Blobstore,java,android,google-app-engine,google-cloud-endpoints,blobstore,Java,Android,Google App Engine,Google Cloud Endpoints,Blobstore,如何使用Mobile Backend Starter或Google Cloud Endpoints将文件从Android上传到Google App Engine Blobstore?与Mobile Backend Starter共享我的到期日 要获取上传和下载URL,您需要将这两个方法添加到CloudBackend.java类中,以便从活动中访问URL: public String getUploadBlobURL(String bucketName, String path, String a
CloudBackend.java
类中,以便从活动中访问URL:
public String getUploadBlobURL(String bucketName, String path, String accessMode) {
String url = null;
try {
url = getMBSEndpoint().blobEndpoint()
.getUploadUrl(bucketName, path, accessMode).execute()
.getShortLivedUrl();
} catch (IOException e) {
e.printStackTrace();
}
return url;
}
public String getDownloadBlobURL(String bucketName, String path) {
String url = null;
try {
url = getMBSEndpoint().blobEndpoint()
.getDownloadUrl(bucketName, path).execute()
.getShortLivedUrl();
} catch (IOException e) {
e.printStackTrace();
}
return url;
}
然后,在标准客户端库的帮助下,您可以使用URL将字节流传输到Google云存储
下面我将给你一些例子来说明如何使用它们
要将文件上载到Google云存储,您可以使用类似的方法:
活动
File fileUp = new File(Environment.getExternalStorageDirectory(), fileName);
new AsyncBlobUploader(this, mProcessingFragment.getCloudBackend()).execute(fileUp);
File fileDown = new File(Environment.getExternalStorageDirectory(),
fileName); //file to create
new AsyncBlobDownloader(imageView, mProcessingFragment.getCloudBackend())
.execute(fileDown);
异步任务
public class AsyncBlobUploader extends AsyncTask<File, Void, String> {
private Context context;
private ProgressDialog pd;
private CloudBackend cb;
public AsyncBlobUploader(Context context, CloudBackend cb) {
this.context = context;
this.cb = cb;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(context, null,
"Loading... Please wait...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setIndeterminate(true);
pd.setCancelable(true);
pd.show();
}
protected String doInBackground(File... files) {
File file = files[0];
String uploadUrl = cb.getUploadBlobURL(bucketName, file.getName(),"PUBLIC_READ_FOR_APP_USERS");
String url = uploadUrl.split("&Signature")[0]; // url without Signature
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody filebody = new FileBody(file,ContentType.create(getMimeType(file
.toString())), file.getName());
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("file", filebody);
httppost.setEntity(multipartEntity.build());
System.out.println( "executing request " + httppost.getRequestLine( ) );
try {
HttpResponse response = httpclient.execute( httppost );
Log.i("response", response.getStatusLine().toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager( ).shutdown( );
return (String) uploadUrl;
}
protected void onPostExecute(String result) {
pd.dismiss();
Log.d("BlobUrl", result);
}
public static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
type = mime.getMimeTypeFromExtension(extension);
}
return type;
}
}
public class AsyncBlobDownloader extends AsyncTask<File, Integer, File> {
private ImageView imageView;
private ProgressDialog pd;
private CloudBackend cb;
public AsyncBlobDownloader(ImageView imageView, CloudBackend cb) {
this.imageView = imageView;
this.cb = cb;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(imageView.getContext(), null,
"Loading... Please wait...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setCancelable(true);
pd.show();
}
protected File doInBackground(File... files) {
File file = files[0];
String downloadUrl = cb.getDownloadBlobURL(bucketName,
file.getName());
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(downloadUrl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.i("Response",
"Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage());
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(file);
byte data[] = new byte[4096];
int count;
while ((count = input.read(data)) != -1) {
if (isCancelled()) {
input.close();
return null;
}
output.write(data, 0, count);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return file;
}
protected void onPostExecute(File result) {
pd.dismiss();
imageView.setImageURI(Uri.fromFile(result));
}
}
异步任务
public class AsyncBlobUploader extends AsyncTask<File, Void, String> {
private Context context;
private ProgressDialog pd;
private CloudBackend cb;
public AsyncBlobUploader(Context context, CloudBackend cb) {
this.context = context;
this.cb = cb;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(context, null,
"Loading... Please wait...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setIndeterminate(true);
pd.setCancelable(true);
pd.show();
}
protected String doInBackground(File... files) {
File file = files[0];
String uploadUrl = cb.getUploadBlobURL(bucketName, file.getName(),"PUBLIC_READ_FOR_APP_USERS");
String url = uploadUrl.split("&Signature")[0]; // url without Signature
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody filebody = new FileBody(file,ContentType.create(getMimeType(file
.toString())), file.getName());
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("file", filebody);
httppost.setEntity(multipartEntity.build());
System.out.println( "executing request " + httppost.getRequestLine( ) );
try {
HttpResponse response = httpclient.execute( httppost );
Log.i("response", response.getStatusLine().toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager( ).shutdown( );
return (String) uploadUrl;
}
protected void onPostExecute(String result) {
pd.dismiss();
Log.d("BlobUrl", result);
}
public static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
type = mime.getMimeTypeFromExtension(extension);
}
return type;
}
}
public class AsyncBlobDownloader extends AsyncTask<File, Integer, File> {
private ImageView imageView;
private ProgressDialog pd;
private CloudBackend cb;
public AsyncBlobDownloader(ImageView imageView, CloudBackend cb) {
this.imageView = imageView;
this.cb = cb;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(imageView.getContext(), null,
"Loading... Please wait...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setCancelable(true);
pd.show();
}
protected File doInBackground(File... files) {
File file = files[0];
String downloadUrl = cb.getDownloadBlobURL(bucketName,
file.getName());
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(downloadUrl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.i("Response",
"Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage());
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(file);
byte data[] = new byte[4096];
int count;
while ((count = input.read(data)) != -1) {
if (isCancelled()) {
input.close();
return null;
}
output.write(data, 0, count);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return file;
}
protected void onPostExecute(File result) {
pd.dismiss();
imageView.setImageURI(Uri.fromFile(result));
}
}
公共类AsyncBlobDownloader扩展了AsyncTask{
私人影像视图;
私营部门;
私有云计算;
公共异步BlobDownloader(ImageView ImageView,CloudBackend cb){
this.imageView=imageView;
this.cb=cb;
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pd=ProgressDialog.show(imageView.getContext(),null,
“正在加载…请稍候…”);
pd.setProgressStyle(ProgressDialog.STYLE_微调器);
pd.可设置可取消(真);
pd.show();
}
受保护文件doInBackground(文件…文件){
文件=文件[0];
String downloadUrl=cb.getDownloadBlobURL(bucketName,
getName());
InputStream输入=null;
OutputStream输出=null;
HttpURLConnection=null;
试一试{
URL=新URL(下载URL);
connection=(HttpURLConnection)url.openConnection();
connection.connect();
if(connection.getResponseCode()!=HttpURLConnection.HTTP\u确定){
Log.i(“响应”,
“服务器返回HTTP”+连接。getResponseCode()
+“”+连接。getResponseMessage());
}
int fileLength=connection.getContentLength();
输入=连接。getInputStream();
输出=新文件输出流(文件);
字节数据[]=新字节[4096];
整数计数;
而((计数=输入。读取(数据))!=-1){
如果(isCancelled()){
input.close();
返回null;
}
输出.写入(数据,0,计数);
}
}捕获(例外e){
e、 printStackTrace();
}最后{
试一试{
if(输出!=null)
output.close();
如果(输入!=null)
input.close();
}捕获(忽略IOException){
}
if(连接!=null)
连接断开();
}
返回文件;
}
受保护的void onPostExecute(文件结果){
pd.解散();
setImageURI(Uri.fromFile(result));
}
}
注意:要使用谷歌云存储,您需要启用计费。您还需要在GCS中创建bucket