【发布时间】:2013-07-28 22:41:22
【问题描述】:
我正在尝试使用 Google APIs Client Library for JavaScript 和 resumable upload type 将文件上传到 Google 云端硬盘。
我成功验证并获取了上传 URI,但在发送实际数据时遇到了问题。如果文件仅包含 ASCII 字符,则文件会成功发送到云端硬盘,但如果是特殊字符 (åäö) 或二进制文件(例如 PNG),则文件会损坏。我的猜测是,在进程的某个地方,文件在客户端被编码为 unicode。
如果我使用“btoa()”将原始数据编码为 base64 并将标头“Content-Encoding: base64”添加到数据发送请求中,则文件上传正常。然而,使用这种方法会增加 33% 的开销,这在计划上传的文件大小为 100MB 到 1GB 时是相当大的。
以下是一些代码示例:
获取可续传的上传 URI:
// Authentication is already done
var request = gapi.client.request({
"path": DRIVE_API_PATH, // "/upload/drive/v2/files"
"method": "POST",
"params": {
"uploadType": "resumable"
},
"headers": {
"X-Upload-Content-Type": self.file.type,
//"X-Upload-Content-Length": self.file.size
// If this is uncommented, the upload fails because the file size is
// different (corrupted file). Manually setting to the corrupted file
// size doesn't give 400 Bad Request.
},
"body": {
// self.file is the file object from <input type="file">
"title": self.file.name,
"mimeType": self.file.type,
"Content-Lenght": self.file.size,
}
});
一次性发送整个文件:
// I read the file using FileReader and readAsBinaryString
// body is the reader.result (or btoa(reader.result))
// and this code is ran after the file has been read
var request = gapi.client.request({
"path": self.resumableUrl, // URI got from previous request
"method": "PUT",
"headers": {
//"Content-Encoding": "base64", // Uploading with base64 works
"Content-Type": self.file.type
},
"body": body
});
我错过了什么吗?是否可以以二进制流上传文件?我是使用 HTML 和 Javascript 上传文件的新手,我还没有找到任何使用可恢复上传的 Google Javascript 库的示例。 SO中有similar question没有答案。
【问题讨论】:
-
这些信息对您的情况有用吗?这是一个 Javascript 库,用于实现 Google Drive 的可恢复上传。 github.com/tanaikech/ResumableUploadForGoogleDrive_js
标签: javascript google-drive-api