我正在尝试使用Google云端硬盘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));
}
授权头是通过调用该gapi.client.getToken().access_token
函数分配的,基本上,这将从gapi调用的响应中获取空对象,然后调用fetch
api来上传文件的实际位!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句