从Google App Engine上传文件到Google云端存储(Java) [英] Upload file to Google cloud storage from Google App Engine (Java)

查看:206
本文介绍了从Google App Engine上传文件到Google云端存储(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能从谷歌应用程序引擎中的servlet上传文件到谷歌云存储?

当我这样做时,Google云存储不知道文件的类型,即我从HTML表单发送的文件。什么是编写HTML / JavaScript和servlet以将文件上传到云存储的正确方法? 解决方案

以下是一个代码示例来自Google用于与Java脚本中的云存储进行交互。它不仅仅是上传,也就是说你可以下载,创建新的存储桶等。下面我添加了我用来上传的函数,这个函数是从这个例子中派生出来的。

 <!DOCTYPE html> 
< html>
< head lang =en>
< meta charset ='utf-8'/>
< script src =https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js>< / script>
< script src =https://apis.google.com/js/client.js>< / script>
< script type =text / javascript>
/ **
*您的Google云端存储项目的项目ID。
* /
var PROJECT ='abcd';
/ **
*在APIs& auth,Credentials页面的Google Developers
* Console中输入Web应用程序的客户端ID。
*在您的Developers Console项目中,添加一个JavaScript起源
*,该起始地位与您将运行
*脚本的域相对应。有关详情,请参阅:
* https://developers.google.com/console/help/new/#generatingoauth2
* /
var clientId ='701111116470-55bj2lkjlkkjkljhe97di22gus5hs3.apps.googleusercontent。 com公司;
/ **
*按照以下
*步骤,从Google Developers Console输入API密钥:
* 1)访问https://cloud.google.com/控制台并选择您的项目
* 2)点击左侧栏中的APIs& auth,然后点击Credentials
* 3)查找Public API Access部分并使用API密钥。如果示例是在本地主机上运行的
*,则删除所有引用者并保存。设置
*应显示允许任何引用者。有关详情,请参阅:
* https://developers.google.com/console/help/new/#generatingdevkeys
* /
var apiKey ='JHJhhguy8786875hghgjbS0nYjcMY';
/ **
*要输入一个或多个认证范围,请参阅API的文档
*。
* /
var scopes ='https://www.googleapis.com/auth/devstorage.full_control';
/ **
*请求参数的常量。使用您的自定义
*信息填充这些值。
* /
var API_VERSION ='v1';
/ **
*输入一个唯一的存储桶名称来创建一个新的存储桶。可以在这里找到
*桶命名的准则:
* https://developers.google.com/storage/docs/bucketnaming
* /
// var BUCKET = 'code-sample-bucket-'+ Date.now();
var BUCKET ='testbucket';
/ **
*通过insertObject方法插入的对象的名称。
* /
var object =;
/ **
*从Developers Console获取此值。点击左栏中的
*Cloud Storage服务,然后选择
*项目仪表板。使用其中一个Google云端存储组标识
*列出并与前缀group-组合以获得字符串
*,如下例所示。
* /
var GROUP =
'group -kjhHJKHJKH897897878jgjghg8728f21c3ff22597efbfc63ccdb8f2294d8fd2561cb9';
/ **
*有效值为user-userId,user-email,group-groupId,group-email,
* allUsers,allAuthenticatedUsers
* /
var ENTITY ='allUsers';
/ **
*有效值为READER,OWNER
* /
var ROLE ='READER';
/ **
*有效值为READER,OWNER
* /
var ROLE_OBJECT ='READER';
/ **
* Google Cloud Storage JavaScript客户端
*库的示例调用列表,以及每个调用的相关说明。
* /
var listApiRequestExplanations = {
'listBuckets':'此API调用查询Google Cloud Storage API'+
'获取您项目中的存储桶列表,并返回结果为'+
'Google云端存储桶列表'',
'listObjects':'此API调用查询Google Cloud Storage API'+
'获取对象列表并将结果作为'+
'返回为Google Cloud Storage对象列表。',
'listBucketsAccessControls':'此API调用查询Google Cloud'+
'存储您的'+
'项目中存储区访问控制列表的API列表,并将结果作为Google Cloud Storage'+
'访问控制列表的列表返回。',
'listObjectsAccessControls ':'此API调用查询Google Cloud'+
'存储API,用于您的'+
'存储桶中对象的访问控制列表列表,并将结果作为Google云端存储'+
'访问控制列表的结果列表。',
'getBucket':'此API调用在您的项目中查询Google Cloud Storage API'+
',并将结果作为'+
'Google云端存储分区返回。',
'getBucketAccessControls':'此API调用查询特定存储桶'+
'上的访问控制列表的Google Cloud'+
'存储API,并将结果作为Google Cloud Storage Access Control List'',
'getObjectAccessControls':'此API调用查询特定对象'+
'上的访问控制列表的Google Cloud'+
'存储API并返回结果为Google云存储访问控制李st'',
'insertBucket':'此API调用使用Google Cloud Storage API'+
'将一个存储桶插入到您的项目中。',
'insertObject':'This API调用使用Google云端存储API'+
'将对象插入到存储桶中'',
'insertBucketAccessControls':'此API使用Google Cloud'+
'存储API插入一个特定存储区'+
'上的访问控制列表,并将结果作为Google云端存储访问控制列表返回。',
'insertObjectAccessControls':'此API使用Google Cloud'+
'存储API将访问控制列表插入特定对象'+
'并将结果作为Google云端存储访问控制列表返回。',
'deleteBucket':'此API使用Google云存储API删除'+
'一个空格',
'deleteObject':'此API使用Google Cloud Storage API删除'+
'对象,并返回一个空响应以指示成功。 '
};
/ **
* Google云端存储API请求,用于检索
*您的Google云端存储项目中的存储列表。
* /
函数listBuckets(){
var request = gapi.client.storage.buckets.list({
'project':PROJECT
});
executeRequest(request,'listBuckets');
}
/ **
* Google云端存储API请求,用于检索
*您的Google云端存储项目中的对象列表。
*
函数listObjects(){
var request = gapi.client.storage.objects.list({
'bucket':BUCKET
});
executeRequest(request,'listObjects');
}
/ **
* Google云端存储API请求,用于检索您的Google云端存储项目中存储桶
*上的访问控制列表。
* /
函数listBucketsAccessControls(){
var request = gapi.client.storage.bucketAccessControls.list({
'bucket':BUCKET
});
executeRequest(request,'listBucketsAccessControls');
}
/ **
* Google Cloud Storage API请求,用于检索您的Google云存储项目中的
*对象的访问控制列表。
* /
函数listObjectsAccessControls(){
var request = gapi.client.storage.objectAccessControls.list({$ b $'bucket':BUCKET,
'object' :object
});
executeRequest(request,'listObjectsAccessControls');
}
/ **
* Google云端存储API请求可以在
*您的Google云端存储项目中检索存储桶。
* /
function getBucket(){
var request = gapi.client.storage.buckets.get({$ b $'bucket':BUCKET
});
executeRequest(request,'getBucket');
}
/ **
* Google Cloud Storage API请求可以在您的Google Cloud Storage项目中检索存储区的存取控制
*列表。
* /
函数getBucketAccessControls(){
var request = gapi.client.storage.bucketAccessControls.get({$ b $'bucket':BUCKET,
'entity' :GROUP
});
executeRequest(request,'getBucketAccessControls');
}
/ **
* Google Cloud Storage API请求,用于检索您的Google Cloud Storage项目中的对象的访问控制
*列表。
* /
函数getObjectAccessControls(){
var request = gapi.client.storage.objectAccessControls.get({$ b $'bucket':BUCKET,
'object' :object,
'entity':GROUP
});
executeRequest(request,'getObjectAccessControls');
}
/ **
* Google云端存储API请求将存储区插入
*您的Google云端存储项目。
* /
函数insertBucket(){
resource = {
'name':BUCKET
};
var request = gapi.client.storage.buckets.insert({$ b $'project':PROJECT,
'resource':resource
});
executeRequest(request,'insertBucket');
}
/ **
* Google Cloud Storage API请求将对象插入
*您的Google Cloud Storage存储分区。
* /
函数insertObject(event){
try {
var fileData = event.target.files [0];
catch {e} {
//从API中选择的'Insert Object'命令选择列表
//显示插入对象按钮,然后退出函数
filePicker .style.display ='block';
return;
}
const boundary ='------- 314159265358979323846';
const delimiter =\r\\\
--+ boundary +\r\\\
;
const close_delim =\r\\\
--+ boundary + - ;
var reader = new FileReader();
reader.readAsBinaryString(fileData);
reader.onload = function(e){
var contentType = fileData.type || 应用程序/八位字节流;
var metadata = {
'name':fileData.name,
'mimeType':contentType
};
var base64Data = btoa(reader.result);
var multipartRequestBody =
delimiter +
'Content-Type:application / json\r\\\
\r\''+
JSON.stringify(metadata)+
分隔符+
'Content-Type:'+ contentType +'\r\\\
'+
'Content-Transfer-Encoding:base64 \\\\''+
'\r\\\
'+
base64Data +
close_delim;
//注意:gapi.client.storage.objects.insert()只能插入
//小对象(小于64k)以支持更大的文件大小
//我们正在使用通用HTTP请求方法gapi.client.request()
var request = gapi.client.request({$ b $'path':'/ upload / storage /'+ API_VERSION +'/ b /'+ BUCKET +'/ o',
'method':'POST',
'params':{'uploadType':'multipart'},
'headers':{
'Content-Type':'multipart / mixed; boundary =''+ boundary +''
},
'body':multipartRequestBody});
//删除主要内容中的当前API结果条目div
listChildren = document.getElementById('main-content')。childNodes;
if(listChildren.length> 1){
listChildren [1] .parentNode.removeChild(listChildren [1]);
}
try {
//执行插入对象请求
executeRequest(request,'insertObject');
//存储插入对象的名称
object = fileData.name;
}
catch(e){
alert('发生错误:'+ e.message);
}
}
}
/ **
* Google云端存储API请求将访问控制列表插入
*您的Google云端存储分区。
* /
函数insertBucketAccessControls(){
resource = {$ b $'entity':ENTITY,
'role':ROLE
};
var request = gapi.client.storage.bucketAccessControls.insert({
'bucket':BUCKET,
'resource':resource
});
executeRequest(request,'insertBucketAccessControls');
}
/ **
* Google云端存储API请求将访问控制列表插入
*您的Google云端存储对象。
$ /
函数insertObjectAccessControls(){
resource = {$ b $'entity':ENTITY,
'role':ROLE_OBJECT
};
var request = gapi.client.storage.objectAccessControls.insert({
'bucket':BUCKET,
'object':object,
'resource':resource
});
executeRequest(request,'insertObjectAccessControls');
}
/ **
* Google Cloud Storage API请求删除Google云端存储分区。
* /
function deleteBucket(){
var request = gapi.client.storage.buckets.delete({$ b $'bucket':BUCKET
});
executeRequest(request,'deleteBucket');
}
/ **
* Google Cloud Storage API请求删除Google Cloud Storage对象。
* /
function deleteObject(){
var request = gapi.client.storage.objects.delete({$ b $'bucket':BUCKET,
'object' :object
});
executeRequest(request,'deleteObject');
}
/ **
*删除主内容div中的当前API结果条目,为您的函数添加条目的
*结果。
* @param {string} apiRequestName示例API请求的名称。
* /
函数updateApiResultEntry(apiRequestName){
listChildren = document.getElementById('main-content')
.childNodes;
if(listChildren.length> 1){
listChildren [1] .parentNode.removeChild(listChildren [1]);

if(apiRequestName!='null'){
window [apiRequestName] .apply(this);
}
}
/ **
*确定选择了哪个API请求,并调用以添加
*的结果条目。
* /
函数runSelectedApiRequest(){
var curElement = document.getElementById('api-selection-options');
var apiRequestName = curElement.options [curElement.selectedIndex] .value;
updateApiResultEntry(apiRequestName);
}
/ **
*绑定事件监听器来处理新选择的API请求。
* /
function addSelectionSwitchingListeners(){
document.getElementById('api-selection-options')
.addEventListener('change',
runSelectedApiRequest,false) ;
}
/ **
*获取JavaScript示例代码片段的模板。
* @param {string}方法Google Cloud Storage请求的名称
* @param {string} params传递给方法
/
的参数getCodeSnippet(method, params){
var objConstruction =//声明你的参数object \\\
;
objConstruction + =var params = {};;
objConstruction + =\\\
\\\
;
var param =//初始​​化你的参数\\\
;
for(i in params){
param + =params ['+ i +'] =;
param + = JSON.stringify(params [i],null,'\t');
param + =;;
param + =\\\
;
}
param + =\\\
;
var methodCall =//请求Google Cloud Storage API \\\
;
methodCall + =var request = gapi.client。 +方法+(params);;
return objConstruction + param + methodCall;
}
/ **
*执行您的Google Cloud Storage请求对象,然后
*将响应插入到页面中。
* @param {string}请求来自Google Cloud Storage JavaScript客户端库的Google Cloud Storage请求对象发布
*。
* @param {string} apiRequestName示例API请求的名称。
* /
函数executeRequest(request,apiRequestName){
request.execute(function(resp){
console.log(resp);
var apiRequestNode = document .createElement('div');
apiRequestNode.id = apiRequestName;
var apiRequestNodeHeader = document.createElement('h2');
apiRequestNodeHeader.innerHTML = apiRequestName;
var apiRequestExplanationNode = document.createElement('div');
apiRequestExplanationNode.id = apiRequestName +'RequestExplanation';
var apiRequestExplanationNodeHeader = document.createElement('h3');
apiRequestExplanationNodeHeader.innerHTML ='API请求解释';
apiRequestExplanationNode.appendChild(apiRequestExplanationNodeHeader);
var apiRequestExplanationEntry = document.createElement( P);
apiRequestExplanationEntry.innerHTML =
listApiRequestExplanations [apiRequestName];
apiRequestExplanationNode.appendChild(apiRequestExplanationEntry);
apiRequestNode.appendChild(apiRequestNodeHeader);
apiRequestNode.appendChild(apiRequestExplanationNode);
var apiRequestCodeSnippetNode = document.createElement('div');
apiRequestCodeSnippetNode.id = apiRequestName +'CodeSnippet';
var apiRequestCodeSnippetHeader = document.createElement('h3');
apiRequestCodeSnippetHeader.innerHTML ='API Request Code Snippet';
apiRequestCodeSnippetNode.appendChild(apiRequestCodeSnippetHeader);
var apiRequestCodeSnippetEntry = document.createElement('pre');
//如果选择的API命令不是'insertObject',请将请求
//参数传递给getCodeSnippet方法调用,如'request.wc.wc.params'
// else pass请求参数为'request.wc.wc'

$ b $ * / if(apiRequestName!='insertObject'){
apiRequestCodeSnippetEntry.innerHTML =
getCodeSnippet(request。 wc.wc.method,request.wc.wc.params);
//选定的API命令不是'insertObject'
//隐藏插入对象按钮
filePicker.style.display ='none';
} else {
apiRequestCodeSnippetEntry.innerHTML =
getCodeSnippet(request.wc.wc.method,request.wc.wc);
} * /


apiRequestCodeSnippetNode.appendChild(apiRequestCodeSnippetEntry);
apiRequestNode.appendChild(apiRequestCodeSnippetNode);
var apiResponseNode = document.createElement('div');
apiResponseNode.id = apiRequestName +'Response';
var apiResponseHeader = document.createElement('h3');
apiResponseHeader.innerHTML ='API Response';
apiResponseNode.appendChild(apiResponseHeader);
var apiResponseEntry = document.createElement('pre');
apiResponseEntry.innerHTML = JSON.stringify(resp,null,'');
apiResponseNode.appendChild(apiResponseEntry);
apiRequestNode.appendChild(apiResponseNode);
var content = document.getElementById('main-content');
content.appendChild(apiRequestNode);
});
}
/ **
*设置所需的API密钥并检查验证状态。
* /
函数handleClientLoad(){
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
/ **
*授权Google Cloud Storage API。
* /
函数checkAuth(){
gapi.auth.authorize({
client_id:clientId,
scope:scopes,
immediate:true
},handleAuthResult);
}
/ **
*处理授权。
* /
函数handleAuthResult(authResult){
var authorizeButton = document.getElementById('authorize-button');
if(authResult&&!authResult.error){
authorizeButton.style.visibility ='hidden';
initializeApi();
filePicker.onchange = insertObject;
} else {
authorizeButton.style.visibility ='';
authorizeButton.onclick = handleAuthClick;
}
}
/ **
*处理授权点击事件。
* /
函数handleAuthClick(event){
gapi.auth.authorize({
client_id:clientId,
scope:scopes,
immediate:false
},handleAuthResult);
返回false;
}
/ **
*加载Google Cloud Storage API。
* /
函数initializeApi(){
gapi.client.load('storage',API_VERSION);
}
/ **
*示例应用程序的驱动程序。
* /
$(window)
.bind('load',function(){
addSelectionSwitchingListeners();
handleClientLoad();
} );
< / script>
< / head>
< body>
<! - 为用户添加一个按钮以点击以启动授权序列 - >
< button id =authorize-buttonstyle =visibility:hidden>授权< /按钮>
< header>
< h1> Google云端存储JavaScript客户端库应用程序< / h1>
< / header>
< label id =api-label>尝试API调用示例!< / label>
< select id =api-selection-options>
< option value =null>
请从下拉菜单中选择一个API调用示例
< / option>
< option value =listBuckets>
列出桶
< / option>
< option value =insertBucket>
插入桶
< / option>
< option value =getBucket>
获取桶
< / option>
< option value =getBucketAccessControls>
获取桶访问控制
< / option>
< option value =insertBucketAccessControls>
插入存储区访问控制
< / option>
< option value =listBucketsAccessControls>
列表桶访问控制列表
< / option>
< option value =insertObject>
插入对象
< / option>
< option value =listObjects>
列出对象
< / option>
< option value =getObjectAccessControls>
获取对象访问控制
< / option>
< option value =insertObjectAccessControls>
插入对象访问控件
< / option>
< option value =listObjectsAccessControls>
列出对象访问控制列表
< / option>
< option value =deleteObject>
删除对象
< / option>
< option value =deleteBucket>
删除桶
< / option>
< / select>
< br />
< input type =fileid =filePickerstyle =display:none/>
< div id =main-content>
< / div>
< / body>
< / html>




以下是上传文件的功能,以上。请注意,它使用JavaScript客户端库与Google API(gapi)进行交互,这意味着您可以通过Google帐户进行身份验证以保护上传( https://developers.google.com/api-client-library/javascript/start/start-js )。



  function uploadFile(fileData,bucket){
var boundary =' - ----- 314159265358979323846' ;
var delimiter =\r\\\
--+ boundary +\r\\\
;
var close_delim =\r\\\
--+ boundary + - ;
var reader = new FileReader();
reader.readAsBinaryString(fileData);

reader.onload = function(e){
var contentType = fileData.type || 应用程序/八位字节流;
var metadata = {
'name':fileData.name,
'mimeType':contentType
};
var base64Data = btoa(reader.result);
var multipartRequestBody =
delimiter +
'Content-Type:application / json\r\\\
\r\''+
JSON.stringify(metadata)+
分隔符+
'Content-Type:'+ contentType +'\r\\\
'+
'Content-Transfer-Encoding:base64 \\\\''+
'\r\\\
'+
base64Data +
close_delim;

var request = gapi.client.request({$ b $'path':'/ upload / storage / v1 / b /'+ bucket +'/ o',
'方法':'POST',
'params':{'uploadType':'multipart'},
'headers':{
'Content-Type':'multipart / mixed; boundary =''+ boundary +'''
},
'body':multipartRequestBody
});

try {
request.execute(function(resp){
if(resp.hasOwnProperty(error)){
//处理错误
} else {
// Treat Success
}
});
}
catch(e){
// Treat Error
}

};


$ / code>

最后,您可以使用云存储的对象更改通知在App引擎中调用任务。您可以传递存储桶和文件名,并通过App Engine处理刚刚上传的文件。 https://cloud.google.com/storage/docs/object-change-通知


How can I upload file from servlet in google app engine to google cloud storage?

When I did it, Google cloud storage didn't know the type of the file, the file I send from an HTML form. What is the correct way to write HTML/JavaScript and servlet to upload a file to cloud storage?

解决方案

Below is a code example from Google for interacting with the Cloud Storage in Java Script. It does much more than uploading, i.e. you can download, create new bucket, etc. Below I've added the function I use to upload which is derived from this example.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset='utf-8' />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script src="https://apis.google.com/js/client.js"></script>
    <script type="text/javascript">
        /**
         * The Project ID of your Google Cloud Storage Project.
         */
        var PROJECT = 'abcd';
        /**
         * Enter a client ID for a web application from the Google Developers
         * Console on the "APIs & auth", "Credentials" page.
         * In your Developers Console project add a JavaScript origin
         * that corresponds to the domain from where you will be running the
         * script. For more info see:
         * https://developers.google.com/console/help/new/#generatingoauth2
         */
        var clientId = '701111116470-55bj2lkjlkkjkljhe97di22gus5hs3.apps.googleusercontent.com';
        /**
         * Enter the API key from the Google Developers Console, by following these
         * steps:
         * 1) Visit https://cloud.google.com/console and select your project
         * 2) Click on "APIs & auth" in the left column and then click "Credentials"
         * 3) Find section "Public API Access" and use the "API key." If sample is
         * being run on localhost then delete all "Referers" and save. Setting
         * should display "Any referer allowed." For more info see:
         * https://developers.google.com/console/help/new/#generatingdevkeys
         */
        var apiKey = 'JHJhhguy8786875hghgjbS0nYjcMY';
        /**
         * To enter one or more authentication scopes, refer to the documentation
         * for the API.
         */
        var scopes = 'https://www.googleapis.com/auth/devstorage.full_control';
        /**
         * Constants for request parameters. Fill these values in with your custom
         * information.
         */
        var API_VERSION = 'v1';
        /**
         * Enter a unique bucket name to create a new bucket. The guidelines for
         * bucket naming can be found here:
         * https://developers.google.com/storage/docs/bucketnaming
         */
        //var BUCKET = 'code-sample-bucket-' + Date.now();
        var BUCKET = 'testbucket';
        /**
         * The name of the object inserted via insertObject method.
         */
        var object = "";
        /**
         * Get this value from the Developers Console. Click on the
         * "Cloud Storage" service in the Left column and then select
         * "Project Dashboard". Use one of the Google Cloud Storage group IDs
         * listed and combine with the prefix "group-" to get a string
         * like the example below.
         */
        var GROUP =
                'group-kjhHJKHJKH897897878jgjghg8728f21c3ff22597efbfc63ccdb8f2294d8fd2561cb9';
        /**
         * Valid values are user-userId, user-email, group-groupId, group-email,
         * allUsers, allAuthenticatedUsers
         */
        var ENTITY = 'allUsers';
        /**
         * Valid values are READER, OWNER
         */
        var ROLE = 'READER';
        /**
         * Valid values are READER, OWNER
         */
        var ROLE_OBJECT = 'READER';
        /**
         * A list of example calls to the Google Cloud Storage JavaScript client
         * library, as well as associated explanations of each call.
         */
        var listApiRequestExplanations = {
            'listBuckets': 'This API call queries the Google Cloud Storage API ' +
            'for a list of buckets in your project, and returns the result as ' +
            'a list of Google Cloud Storage buckets.',
            'listObjects': 'This API call queries the Google Cloud Storage API ' +
            'for a list of objects in your bucket, and returns the result as ' +
            'a list of Google Cloud Storage objects.',
            'listBucketsAccessControls': 'This API call queries the Google Cloud ' +
            'Storage API for the list of access control lists on buckets in your ' +
            'project and returns the result as a list of Google Cloud Storage ' +
            'Access Control Lists.',
            'listObjectsAccessControls': 'This API call queries the Google Cloud ' +
            'Storage API for the list of access control lists on objects in your ' +
            'bucket and returns the result as a list of Google Cloud Storage ' +
            'Access Control Lists.',
            'getBucket': 'This API call queries the Google Cloud Storage API ' +
            'for a bucket in your project, and returns the result as a ' +
            'Google Cloud Storage bucket.',
            'getBucketAccessControls': 'This API call queries the Google Cloud ' +
            'Storage API for the access control list on a specific bucket ' +
            'and returns the result as a Google Cloud Storage Access Control List.',
            'getObjectAccessControls': 'This API call queries the Google Cloud ' +
            'Storage API for the access control list on a specific object ' +
            'and returns the result as a Google Cloud Storage Access Control List.',
            'insertBucket': 'This API call uses the Google Cloud Storage API ' +
            'to insert a bucket into your project.',
            'insertObject': 'This API call uses the Google Cloud Storage API ' +
            'to insert an object into your bucket.',
            'insertBucketAccessControls': 'This API uses the Google Cloud ' +
            'Storage API to insert an access control list on a specific bucket ' +
            'and returns the result as a Google Cloud Storage Access Control List.',
            'insertObjectAccessControls': 'This API uses the Google Cloud ' +
            'Storage API to insert an access control list on a specific object ' +
            'and returns the result as a Google Cloud Storage Access Control List.',
            'deleteBucket': 'This API uses the Google Cloud Storage API to delete ' +
            'an empty bucket and returns an empty response to indicate success.',
            'deleteObject': 'This API uses the Google Cloud Storage API to delete ' +
            'an object and returns an empty response to indicate success.'
        };
        /**
         * Google Cloud Storage API request to retrieve the list of buckets in
         * your Google Cloud Storage project.
         */
        function listBuckets() {
            var request = gapi.client.storage.buckets.list({
                'project': PROJECT
            });
            executeRequest(request, 'listBuckets');
        }
        /**
         * Google Cloud Storage API request to retrieve the list of objects in
         * your Google Cloud Storage project.
         */
        function listObjects() {
            var request = gapi.client.storage.objects.list({
                'bucket': BUCKET
            });
            executeRequest(request, 'listObjects');
        }
        /**
         * Google Cloud Storage API request to retrieve the access control list on
         * a bucket in your Google Cloud Storage project.
         */
        function listBucketsAccessControls() {
            var request = gapi.client.storage.bucketAccessControls.list({
                'bucket': BUCKET
            });
            executeRequest(request, 'listBucketsAccessControls');
        }
        /**
         * Google Cloud Storage API request to retrieve the access control list on
         * an object in your Google Cloud Storage project.
         */
        function listObjectsAccessControls() {
            var request = gapi.client.storage.objectAccessControls.list({
                'bucket': BUCKET,
                'object': object
            });
            executeRequest(request, 'listObjectsAccessControls');
        }
        /**
         * Google Cloud Storage API request to retrieve a bucket in
         * your Google Cloud Storage project.
         */
        function getBucket() {
            var request = gapi.client.storage.buckets.get({
                'bucket': BUCKET
            });
            executeRequest(request, 'getBucket');
        }
        /**
         * Google Cloud Storage API request to retrieve a bucket's Access Control
         * List in your Google Cloud Storage project.
         */
        function getBucketAccessControls() {
            var request = gapi.client.storage.bucketAccessControls.get({
                'bucket': BUCKET,
                'entity': GROUP
            });
            executeRequest(request, 'getBucketAccessControls');
        }
        /**
         * Google Cloud Storage API request to retrieve an object's Access Control
         * List in your Google Cloud Storage project.
         */
        function getObjectAccessControls() {
            var request = gapi.client.storage.objectAccessControls.get({
                'bucket': BUCKET,
                'object': object,
                'entity': GROUP
            });
            executeRequest(request, 'getObjectAccessControls');
        }
        /**
         * Google Cloud Storage API request to insert a bucket into
         * your Google Cloud Storage project.
         */
        function insertBucket() {
            resource = {
                'name': BUCKET
            };
            var request = gapi.client.storage.buckets.insert({
                'project': PROJECT,
                'resource': resource
            });
            executeRequest(request, 'insertBucket');
        }
        /**
         * Google Cloud Storage API request to insert an object into
         * your Google Cloud Storage bucket.
         */
        function insertObject(event) {
            try{
                var fileData = event.target.files[0];
            }
            catch(e) {
                //'Insert Object' selected from the API Commands select list
                //Display insert object button and then exit function
                filePicker.style.display = 'block';
                return;
            }
            const boundary = '-------314159265358979323846';
            const delimiter = "\r\n--" + boundary + "\r\n";
            const close_delim = "\r\n--" + boundary + "--";
            var reader = new FileReader();
            reader.readAsBinaryString(fileData);
            reader.onload = function(e) {
                var contentType = fileData.type || 'application/octet-stream';
                var metadata = {
                    'name': fileData.name,
                    'mimeType': contentType
                };
                var base64Data = btoa(reader.result);
                var multipartRequestBody =
                        delimiter +
                        'Content-Type: application/json\r\n\r\n' +
                        JSON.stringify(metadata) +
                        delimiter +
                        'Content-Type: ' + contentType + '\r\n' +
                        'Content-Transfer-Encoding: base64\r\n' +
                        '\r\n' +
                        base64Data +
                        close_delim;
                //Note: gapi.client.storage.objects.insert() can only insert
                //small objects (under 64k) so to support larger file sizes
                //we're using the generic HTTP request method gapi.client.request()
                var request = gapi.client.request({
                    'path': '/upload/storage/' + API_VERSION + '/b/' + BUCKET + '/o',
                    'method': 'POST',
                    'params': {'uploadType': 'multipart'},
                    'headers': {
                        'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
                    },
                    'body': multipartRequestBody});
                //Remove the current API result entry in the main-content div
                listChildren = document.getElementById('main-content').childNodes;
                if (listChildren.length > 1) {
                    listChildren[1].parentNode.removeChild(listChildren[1]);
                }
                try{
                    //Execute the insert object request
                    executeRequest(request, 'insertObject');
                    //Store the name of the inserted object
                    object = fileData.name;
                }
                catch(e) {
                    alert('An error has occurred: ' + e.message);
                }
            }
        }
        /**
         * Google Cloud Storage API request to insert an Access Control List into
         * your Google Cloud Storage bucket.
         */
        function insertBucketAccessControls() {
            resource = {
                'entity': ENTITY,
                'role': ROLE
            };
            var request = gapi.client.storage.bucketAccessControls.insert({
                'bucket': BUCKET,
                'resource': resource
            });
            executeRequest(request, 'insertBucketAccessControls');
        }
        /**
         * Google Cloud Storage API request to insert an Access Control List into
         * your Google Cloud Storage object.
         */
        function insertObjectAccessControls() {
            resource = {
                'entity': ENTITY,
                'role': ROLE_OBJECT
            };
            var request = gapi.client.storage.objectAccessControls.insert({
                'bucket': BUCKET,
                'object': object,
                'resource': resource
            });
            executeRequest(request, 'insertObjectAccessControls');
        }
        /**
         * Google Cloud Storage API request to delete a Google Cloud Storage bucket.
         */
        function deleteBucket() {
            var request = gapi.client.storage.buckets.delete({
                'bucket': BUCKET
            });
            executeRequest(request, 'deleteBucket');
        }
        /**
         * Google Cloud Storage API request to delete a Google Cloud Storage object.
         */
        function deleteObject() {
            var request = gapi.client.storage.objects.delete({
                'bucket': BUCKET,
                'object': object
            });
            executeRequest(request, 'deleteObject');
        }
        /**
         * Removes the current API result entry in the main-content div, adds the
         * results of the entry for your function.
         * @param {string} apiRequestName The name of the example API request.
         */
        function updateApiResultEntry(apiRequestName) {
            listChildren = document.getElementById('main-content')
                    .childNodes;
            if (listChildren.length > 1) {
                listChildren[1].parentNode.removeChild(listChildren[1]);
            }
            if (apiRequestName != 'null') {
                window[apiRequestName].apply(this);
            }
        }
        /**
         * Determines which API request has been selected, and makes a call to add
         * its result entry.
         */
        function runSelectedApiRequest() {
            var curElement = document.getElementById('api-selection-options');
            var apiRequestName = curElement.options[curElement.selectedIndex].value;
            updateApiResultEntry(apiRequestName);
        }
        /**
         * Binds event listeners to handle a newly selected API request.
         */
        function addSelectionSwitchingListeners() {
            document.getElementById('api-selection-options')
                    .addEventListener('change',
                    runSelectedApiRequest, false);
        }
        /**
         * Template for getting JavaScript sample code snippets.
         * @param {string} method The name of the Google Cloud Storage request
         * @param {string} params The parameters passed to method
         */
        function getCodeSnippet(method, params) {
            var objConstruction = "// Declare your parameter object\n";
            objConstruction += "var params = {};";
            objConstruction += "\n\n";
            var param = "// Initialize your parameters \n";
            for (i in params) {
                param += "params['" + i + "'] = ";
                param += JSON.stringify(params[i], null, '\t');
                param += ";";
                param += "\n";
            }
            param += "\n";
            var methodCall = "// Make a request to the Google Cloud Storage API \n";
            methodCall += "var request = gapi.client." + method + "(params);";
            return objConstruction + param + methodCall;
        }
        /**
         * Executes your Google Cloud Storage request object and, subsequently,
         * inserts the response into the page.
         * @param {string} request A Google Cloud Storage request object issued
         *    from the Google Cloud Storage JavaScript client library.
         * @param {string} apiRequestName The name of the example API request.
         */
        function executeRequest(request, apiRequestName) {
            request.execute(function(resp) {
                console.log(resp);
                var apiRequestNode = document.createElement('div');
                apiRequestNode.id = apiRequestName;
                var apiRequestNodeHeader = document.createElement('h2');
                apiRequestNodeHeader.innerHTML = apiRequestName;
                var apiRequestExplanationNode = document.createElement('div');
                apiRequestExplanationNode.id = apiRequestName + 'RequestExplanation';
                var apiRequestExplanationNodeHeader = document.createElement('h3');
                apiRequestExplanationNodeHeader.innerHTML = 'API Request Explanation';
                apiRequestExplanationNode.appendChild(apiRequestExplanationNodeHeader);
                var apiRequestExplanationEntry = document.createElement('p');
                apiRequestExplanationEntry.innerHTML =
                        listApiRequestExplanations[apiRequestName];
                apiRequestExplanationNode.appendChild(apiRequestExplanationEntry);
                apiRequestNode.appendChild(apiRequestNodeHeader);
                apiRequestNode.appendChild(apiRequestExplanationNode);
                var apiRequestCodeSnippetNode = document.createElement('div');
                apiRequestCodeSnippetNode.id = apiRequestName + 'CodeSnippet';
                var apiRequestCodeSnippetHeader = document.createElement('h3');
                apiRequestCodeSnippetHeader.innerHTML = 'API Request Code Snippet';
                apiRequestCodeSnippetNode.appendChild(apiRequestCodeSnippetHeader);
                var apiRequestCodeSnippetEntry = document.createElement('pre');
                //If the selected API command is not 'insertObject', pass the request
                //paramaters to the getCodeSnippet method call as 'request.wc.wc.params'
                //else pass request paramaters as 'request.wc.wc'


/*                if (apiRequestName != 'insertObject') {
                    apiRequestCodeSnippetEntry.innerHTML =
                            getCodeSnippet(request.wc.wc.method, request.wc.wc.params);
                    //Selected API Command is not 'insertObject'
                    //hide insert object button
                    filePicker.style.display = 'none';
                } else {
                    apiRequestCodeSnippetEntry.innerHTML =
                            getCodeSnippet(request.wc.wc.method, request.wc.wc);
                }*/


                apiRequestCodeSnippetNode.appendChild(apiRequestCodeSnippetEntry);
                apiRequestNode.appendChild(apiRequestCodeSnippetNode);
                var apiResponseNode = document.createElement('div');
                apiResponseNode.id = apiRequestName + 'Response';
                var apiResponseHeader = document.createElement('h3');
                apiResponseHeader.innerHTML = 'API Response';
                apiResponseNode.appendChild(apiResponseHeader);
                var apiResponseEntry = document.createElement('pre');
                apiResponseEntry.innerHTML = JSON.stringify(resp, null, ' ');
                apiResponseNode.appendChild(apiResponseEntry);
                apiRequestNode.appendChild(apiResponseNode);
                var content = document.getElementById('main-content');
                content.appendChild(apiRequestNode);
            });
        }
        /**
         * Set required API keys and check authentication status.
         */
        function handleClientLoad() {
            gapi.client.setApiKey(apiKey);
            window.setTimeout(checkAuth, 1);
        }
        /**
         * Authorize Google Cloud Storage API.
         */
        function checkAuth() {
            gapi.auth.authorize({
                client_id: clientId,
                scope: scopes,
                immediate: true
            }, handleAuthResult);
        }
        /**
         * Handle authorization.
         */
        function handleAuthResult(authResult) {
            var authorizeButton = document.getElementById('authorize-button');
            if (authResult && !authResult.error) {
                authorizeButton.style.visibility = 'hidden';
                initializeApi();
                filePicker.onchange = insertObject;
            } else {
                authorizeButton.style.visibility = '';
                authorizeButton.onclick = handleAuthClick;
            }
        }
        /**
         * Handle authorization click event.
         */
        function handleAuthClick(event) {
            gapi.auth.authorize({
                client_id: clientId,
                scope: scopes,
                immediate: false
            }, handleAuthResult);
            return false;
        }
        /**
         * Load the Google Cloud Storage API.
         */
        function initializeApi() {
            gapi.client.load('storage', API_VERSION);
        }
        /**
         * Driver for sample application.
         */
        $(window)
                .bind('load', function() {
                    addSelectionSwitchingListeners();
                    handleClientLoad();
                });
    </script>
</head>
<body>
<!--Add a button for the user to click to initiate auth sequence -->
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<header>
    <h1>Google Cloud Storage JavaScript Client Library Application</h1>
</header>
<label id="api-label">Try a sample API call!</label>
<select id="api-selection-options">
    <option value="null">
        Please select an example API call from the dropdown menu
    </option>
    <option value="listBuckets">
        List Buckets
    </option>
    <option value="insertBucket">
        Insert Bucket
    </option>
    <option value="getBucket">
        Get Bucket
    </option>
    <option value="getBucketAccessControls">
        Get Bucket Access Controls
    </option>
    <option value="insertBucketAccessControls">
        Insert Bucket Access Controls
    </option>
    <option value="listBucketsAccessControls">
        List Buckets Access Control List
    </option>
    <option value="insertObject">
        Insert Object
    </option>
    <option value="listObjects">
        List Objects
    </option>
    <option value="getObjectAccessControls">
        Get Object Access Controls
    </option>
    <option value="insertObjectAccessControls">
        Insert Object Access Controls
    </option>
    <option value="listObjectsAccessControls">
        List Objects Access Control List
    </option>
    <option value="deleteObject">
        Delete Object
    </option>
    <option value="deleteBucket">
        Delete Bucket
    </option>
</select>
<br/>
<input type="file" id="filePicker" style="display: none" />
<div id="main-content">
</div>
</body>
</html>

Below is the function to upload a file, fully inspired from the example above. Note that it uses the JavaScript client library to interact with Google API (gapi), which means that you can secure the upload with authentication via google accounts (https://developers.google.com/api-client-library/javascript/start/start-js).

function uploadFile(fileData, bucket) {
    var boundary = '-------314159265358979323846';
    var delimiter = "\r\n--" + boundary + "\r\n";
    var close_delim = "\r\n--" + boundary + "--";
    var reader = new FileReader();
    reader.readAsBinaryString(fileData);

    reader.onload = function (e) {
        var contentType = fileData.type || 'application/octet-stream';
        var metadata = {
            'name': fileData.name,
            'mimeType': contentType
        };
        var base64Data = btoa(reader.result);
        var multipartRequestBody =
                delimiter +
                'Content-Type: application/json\r\n\r\n' +
                JSON.stringify(metadata) +
                delimiter +
                'Content-Type: ' + contentType + '\r\n' +
                'Content-Transfer-Encoding: base64\r\n' +
                '\r\n' +
                base64Data +
                close_delim;

        var request = gapi.client.request({
            'path': '/upload/storage/v1/b/' + bucket + '/o',
            'method': 'POST',
            'params': {'uploadType': 'multipart'},
            'headers': {
                'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
            },
            'body': multipartRequestBody
        });

        try {
            request.execute(function (resp) {
                if (resp.hasOwnProperty("error")) {
                    //Treat Error
                } else {
                    //Treat Success
                }
            });
        }
        catch (e) {
            //Treat Error
        }

    };

}

Finally, you can use the Object Change Notification of Cloud Storage to call a task in App engine. You can pass the bucket and file name and treat the file that was just uploaded via App Engine. https://cloud.google.com/storage/docs/object-change-notification

这篇关于从Google App Engine上传文件到Google云端存储(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆