我需要将文件从浏览器上传到我的Google云端硬盘。这是我的上传代码:(files
是从<input type="file">
)
var boundary = "foo_bar_baz";
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
var contentType = doc.mimeType;
var metadata = {
"title": doc.name,
"mimeType": doc.mimeType
};
var reader = new FileReader();
reader.onload = function(e){
var multipartRequestBody =
delimiter + 'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter + 'Content-Type: ' + contentType + '\r\n' + '\r\n' +
e.target.result +
close_delim;
$.ajax({
url: 'https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart',
type: 'POST',
headers: {
"Authorization": 'Bearer ' + luminDriveAccessToken,
"Content-Type": 'multipart/related; boundary="'+ boundary + '"'
},
success: function() {
console.log('>>> Done uploading.');
},
error: _handleUploadErrors,
data: multipartRequestBody,
cache: false,
contentType: false,
processData: false,
crossDomain: true
});
};
reader.readAsBinaryString(files[0]);
当我运行此脚本时,该文件已上传到我的Google云端硬盘(正确的标题,正确的mimeType)但文件内容已损坏(Google云端硬盘无法打开它)。当我将文件下载到我的计算机时,我也无法打开它,并且我意识到下载的文件的大小比原来的 大得多(例如.docx文件:与11.3KB相比,15.4KB。
所以我想问题是在将文件内容发送到服务器之前与文件内容有关。但我还不知道如何修复它。希望你们能帮忙!
答案 0 :(得分:0)
我通过将读者的结果转换为base64Data然后将 Content-Transfer-Encoding:base64 添加到请求正文来找出解决方案。
reader.onload = function(e){
var base64Data = btoa(e.target.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;
$.ajax({
url: 'https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart',
type: 'POST',
headers: {
"Authorization": 'Bearer ' + ACCESS_TOKEN,
"Content-Type": 'multipart/related; boundary="'+ boundary + '"'
},
success: function() {
// TODO XIN
console.log('>>> DONE');
},
error: _handleUploadErrors,
data: multipartRequestBody,
cache: false,
contentType: false,
processData: false,
crossDomain: true
});
};