问题描述
这是我的代码的结构,我试图在对象“ formData.append”中发送名称,但未成功。
文档表明:请随身携带。
文档链接: https://developers.google.com/drive/api/v3/reference/files/create- https://developers.google.com/drive/api/v3/manage-uploads#http_1
我得到了这个答案。
{ “ kind”:“ drive#file”, “ id”:“ 1uz_NN-IyoiPzaheAiKIJu6qlB7ZfxIX2”, “ name”:“无标题”, “ mimeType”:“应用程序/ x-www-form-urlencoded” }
-我将不胜感激
Upload.prototype.doUpload = function () {
var that = this;
var formData = new FormData();
formData.append("file",this.file);
formData.append("upload_file",true);
formData.append("name","test_file");
$.ajax({
type: "POST",beforeSend: function(request) {
request.setRequestHeader("Authorization","Bearer" + " " + localStorage.getItem("accesstoken"));
},url: "https://www.googleapis.com/upload/drive/v3/files",data:{
uploadType:"multipart"
},success: function (data) {
console.log(data);
},error: function (error) {
console.log(error);
},async: true,data: formData,cache: false,processData: false,timeout: 60000
});
};
解决方法
该修改如何?
修改点:
- 似乎无法使用
$ firebase emulators:start --inspect-functions
向httpGet = async (theUrl: string) => { const promise = new Promise((resolve,reject) => { const xmlhttp = new XMLHttpRequest(); //not supporting IE 6 or below xmlhttp.onreadystatechange = () => { if (xmlhttp.readyState==4 && xmlhttp.status==200) { resolve(xmlhttp.responseText); } } xmlhttp.open("GET",theUrl,false); xmlhttp.send(); }); const data = await promise; return data; }
直接请求ajax。因此,在这种情况下,需要创建multipart/form-data
的结构并将其作为数据发送。- 在脚本中,仅文件内容被上传而没有文件元数据。这样,上传的文件就没有文件名了。在这种情况下,需要使用
FormData()
上传文件内容和文件元数据。
- 在脚本中,仅文件内容被上传而没有文件元数据。这样,上传的文件就没有文件名了。在这种情况下,需要使用
- 您的脚本中有
multipart/form-data
的2个属性。
当以上几点反映到您的脚本时,它如下所示。
修改后的脚本:
multipart/form-data
注意:
- 在此修改后的脚本中,
- 它假定脚本中的
data
是blob。 - 您的访问令牌可用于将文件上传到Google云端硬盘。
- 它假定脚本中的
- 使用
Upload.prototype.doUpload = function () { const file = this.file; // It supposes that "this.file" is the blob. const fr = new FileReader(); fr.readAsDataURL(file); fr.onload = function() { const boundary = "xxxxxxxxxx"; let data = "--" + boundary + "\n"; data += "Content-Type: application/json; charset=UTF-8\n\n"; data += JSON.stringify({name: "test_file"}) + "\n"; data += "--" + boundary + "\n"; data += "Content-Transfer-Encoding: base64\n\n"; data += fr.result.split(",")[1] + "\n"; data += "--" + boundary + "--"; $.ajax({ type: "POST",beforeSend: function(request) { request.setRequestHeader("Authorization","Bearer" + " " + localStorage.getItem("accessToken")); request.setRequestHeader("Content-Type","multipart/related; boundary=" + boundary); },url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",success: function (data) { console.log(data); },error: function (error) { console.log(error); },async: true,data: data,cache: false,processData: false,timeout: 60000 }); } }
时,最大文件大小为5 MB。请注意这一点。