问题描述
我有一个html表单,我将一个媒体文件上传到Google驱动器并返回了文件。 这是我的代码:
<form id="form"> <input name="file" id="uploadfile" type="file"> <input name="filename" id="filename" type="text"> <input id="submit" type="submit"> </form> <script> const form = document.getElementById('form'); form.addEventListener('submit',e => { e.preventDefault(); const file = form.file.files[0]; const fr = new FileReader(); fr.readAsArrayBuffer(file); fr.onload = f => { const url = "https://script.google.com/macros/s/###/exec"; // <--- Please set the URL of Web Apps. const qs = new URLSearchParams({filename: form.filename.value || file.name,mimeType: file.type}); fetch(`${url}?${qs}`,{method: "POST",body: JSON.stringify([...new Int8Array(f.target.result)])}) .then(res => res.json()) .then(e => console.log("https://drive.google.com/uc?export=download&id=" + e.fileId)) .catch(err => console.log(err)); } }); </script>
@H_404_5@现在,当我上传example.mp3并在textinput字段中输入stackoverflow时,我会收到一个下载链接。我希望届时将要下载的文件是stackoverflow.mp3,但只有它的stackoverflow,文件类型结尾丢失。有人看到我在那里想念什么吗?
无论如何,我想返回的是Google驱动器中文件的最终链接或直接链接。 (我不知道这个词,对不起我的英语不好)
如果您单击链接,我想在浏览器中打开文件,我希望您可以在webview中播放声音,就像在这里:https://files.freemusicarchive.org/storage-freemusicarchive-org/music/Creative_Commons/Dead_Combo/CC_Affiliates_Mixtape_1/Dead_Combo_-_01_-_Povo_Que_Cas_Descalo.mp3
如何更改我的JavaScript以接收此类链接?
——————编辑————
一个stackoverflow用户描述了如何获取我需要的链接。如何在脚本中放置此步骤?
我试图在Google Actions的SSML音频标签中完成此操作。上述步骤似乎都不起作用。我终于找到了解决方案。
从共享链接https://drive.google.com/file/d/your_file_id/view?usp=sharing
获取文件ID将直接链接粘贴到Web浏览器中,然后按Enter键
在浏览器重定向后复制结果URL注意:这将是一个更长的URL,看起来像这样:https://doc-XX-XX-docs.googleusercontent.com/docs/securesc/XXXXXXXXXXXXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXX/000000000000000/0000000000000000000000/*/your_file_id?e=open
使用此最终到达网址是我可以使上传的声音文件与Google上的Actions一起使用的唯一方法。
解决方法
我认为文件类型保存在Google云端硬盘中。但是,当下载文件时,我认为由于没有扩展名,文件类型可能未知。那么上传文件时添加扩展名又如何呢?
修改脚本后,它如下所示。
修改后的脚本:
从:至:fr.onload = f => { const url = "https://script.google.com/macros/s/###/exec"; // <--- Please set the URL of Web Apps. const qs = new URLSearchParams({filename: form.filename.value || file.name,mimeType: file.type}); fetch(`${url}?${qs}`,{method: "POST",body: JSON.stringify([...new Int8Array(f.target.result)])}) .then(res => res.json()) .then(e => console.log("https://drive.google.com/uc?export=download&id=" + e.fileId)) .catch(err => console.log(err)); }
fr.onload = f => { // I added below script. let newName = form.filename.value; const orgName = file.name; if (orgName.includes(".")) { const orgExt = orgName.split(".").pop(); if (orgExt != newName.split(".").pop()) { newName = newName ? `${newName}.${orgExt}` : orgName; } } const url = "https://script.google.com/macros/s/###/exec"; const qs = new URLSearchParams({filename: newName,mimeType: file.type}); // Modified fetch(`${url}?${qs}`,body: JSON.stringify([...new Int8Array(f.target.result)])}) .then(res => res.json()) .then(e => console.log(e.fileUrl)) // <--- You can retrieve the returned value here. .catch(err => console.log(err)); }