我正在尝试使用以下方式将文件上传到 Google 云端硬盘适用于 JavaScript 的 Google API 客户端库 and 可断点上传类型.
我成功进行了身份验证并获取了上传 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 没有答案。