问题描述
我需要从浏览器上传文件到我的Google云端硬盘。这是我的上传代码:( files
是一个从>< input type =file>
)
I need to upload a file from browser to my Google Drive. This is my upload code: (files
is an array of files get from <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 Drive无法打开它)。当我将文件下载到我的电脑时,我无法打开它,我意识到下载的文件的大小比原始大小 (例如.docx文件的大小: 15.4KB与11.3KB相比)。
所以我猜这个问题在发送到服务器之前与文件内容有关。但我不知道如何解决它。希望你们能帮上忙!
When I run this script, the file got uploaded to my Google Drive (correct title, correct mimeType) but the file content is broken (Google Drive can't open it). When I download the file to my computer, I can't open it either and I realize that the downloaded file's size is slighly bigger than the original one (for example of a .docx file: 15.4KB in comparison with 11.3KB).
So I guess the problem is related to the file content before sending it to the server. But I don't know how to fix it yet. Hope you guys could help !
推荐答案
通过将读者的结果转换为base64Data,然后添加 Content-Transfer -Encoding:base64 到请求的主体。
I find out the solution by converting reader's result to base64Data then add Content-Transfer-Encoding: base64 to the body of the request.
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
});
};
这篇关于驱动REST API - jquery多部分文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!