我正在尝试使用 Google Drive API 上传一个文件,我的元数据是正确的,我想确保实际的文件内容在那里。我有一个简单的页面设置,如下所示:
<div id="upload">
<h6>File Upload Operations</h6>
<input type="file" placeholder='file' name='fileToUpload'>
<button id='uploadFile'>Upload File</button>
</div>
我有一个 javascript 设置,提示用户先登录,然后他们可以上传文件。这是代码:(目前只上传文件元数据....)
let uploadButton = document.getElementById('uploadFile');
uploadButton.onclick = uploadFile;
const uploadFile = () => {
let ftu = document.getElementsByName('fileToUpload')[0].files[0];
console.dir(ftu);
gapi.client.drive.files.create({
'content-type': 'application/json;charset=utf-8',
uploadType: 'multipart',
name: ftu.name,
mimeType: ftu.type,
fields: 'id, name, kind'
}).then(response => {
console.dir(response);
console.log(`File: ${ftu.name} with MimeType of: ${ftu.type}`);
//Need code to upload the file contents......
});
};
首先,我更熟悉后端,所以从 <input type='file'>
中以位的形式获取文件标签对我来说有点模糊。从好的方面来说,元数据就在那里。如何获取文件内容到 api?
最佳答案
因此,根据我在为期三天的搜索中找到的一些资源,该文件根本无法通过 gapi 客户端上传。它必须通过真正的 REST HTTP 调用上传。那么让我们使用fetch
吧!
const uploadFile = () => {
//initialize file data from the dom
let ftu = document.getElementsByName('fileToUpload')[0].files[0];
let file = new Blob([ftu]);
//this is to ensure the file is in a format that can be understood by the API
gapi.client.drive.files.create({
'content-type': 'application/json',
uploadType: 'multipart',
name: ftu.name,
mimeType: ftu.type,
fields: 'id, name, kind, size'
}).then(apiResponse => {
fetch(`https://www.googleapis.com/upload/drive/v3/files/${response.result.id}`, {
method: 'PATCH',
headers: new Headers({
'Authorization': `Bearer ${gapi.client.getToken().access_token}`,
'Content-Type': ftu.type
}),
body: file
}).then(res => console.log(res));
}
授权 header 是通过调用 gapi.client.getToken().access_token
函数分配的,基本上这从 gapi 调用的响应中获取空对象并调用 fetch
用于上传文件的实际位的 api!
关于javascript - Google Drive API 和从浏览器上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53839499/