3
我試圖將Google Drive可恢復文件上傳/更新與我的應用程序集成。但是,當我更新文件時,文件正在以編碼格式進行更新,它並未採取實際內容。編碼格式適用於分段uploadType,但相同內容不適用於可恢復上傳。請找到下面的細節Google Drive可恢復文件上傳問題,使用JavaScript API
步驟1:此處開始可恢復會話
function uploadFile(fileData) {
var accessToken = 'ya29.nwI5Em6UnYGHvVzVx7lBk5tD-xzFl4_JG3_c-_t4FJ3owll_8i_rL5M17LFV6VlF7QE';
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
var contentType = fileData.type || 'application/octet-stream';
var metadata = {
'name': fileData.name,
'mimeType': contentType,
'Content-Type': contentType,
'Content-Length': fileData.size
};
var request = gapi.client.request({
'path' : 'upload/drive/v3/files',
'method' : 'POST',
'params' : {'uploadType':'resumable'},
'headers' : {
'X-Upload-Content-Type' : fileData.type,
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer ' + accessToken,
},
'body' : metadata
});
request.execute(function(resp, raw_resp) {
var locationUrl = JSON.parse(raw_resp).gapiRequest.data.headers.location;
console.log(locationUrl);
uploadToLocationUrl(locationUrl, fileData);
});
}
高達它的優良我越來越位置URL,然後調用上傳文件的功能。
步驟2:可恢復的會話發起請求
function uploadToLocationUrl(locationUrl, fileData)
{
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,
'Content-Type': contentType,
'Content-Length': fileData.size
};
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 requestPost = gapi.client.request({
'path' : locationUrl,
'method' : 'PUT',
'headers' : {
'X-Upload-Content-Length' : fileData.size
},
'body' : multipartRequestBody
});
console.log(requestPost);
requestPost.execute(function(resp, raw_resp) {
console.log(resp);
});
}
}
結果:谷歌更新的文件驅動
---------314159265358979323846
Content-Type: application/json
{"name":"api.txt","mimeType":"text/plain"}
---------314159265358979323846
Content-Type: text/plain
Content-Transfer-Encoding: base64
MSkgTmVlZCBhbiBhcGkgd2hpY2ggd2lsbCByZXR1cm4gYWxsIGxlYWRzIGVtYWlsIGlkLg0KMikgTmVlZCBhbiBhcGkgdG8gY29udmVydCBtdWx0aXBsZSBjb250YWN0IGludG8gbGVhZC4NCjMpIE5lZWQgYW4gYXBpIGZvciBnb29nbGUgc2lnbiBpbi4vLyBkb24ndCBkaXNjdXNzIGFib3V0IHRoaXMgb25lIG5vdywgZmlyc3Qgd2Ugd2lsbCBkaXNjdXNzIGFib3V0IHRoaXMgQVBJLg==
---------314159265358979323846--
謝謝。