[英]How to get a File() or Blob() from an URL in javascript?
我嘗試從 URL(使用ref().put(file)
)(www.example.com/img.jpg)將圖像上傳到 Firebase 存儲。
為此,我需要一個 File 或 Blob,但每當我嘗試new File(url)
時,它都會顯示“沒有足夠的參數”......
編輯:我實際上想上傳整個文件目錄,這就是為什么我不能通過控制台上傳它們
嘗試使用fetch API 。 你可以像這樣使用它:
fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg') .then(res => res.blob()) // Gets the response and returns it as a blob .then(blob => { // Here's where you get access to the blob // And you can use it for whatever you want // Like calling ref().put(blob) // Here, I use it to make an image appear on the page let objectURL = URL.createObjectURL(blob); let myImage = new Image(); myImage.src = objectURL; document.getElementById('myImg').appendChild(myImage) });
<div id="myImg"></div>
截至 2022 年 7 月,fetch API 在全球擁有約97% 的瀏覽器支持,基本上只有 IE 缺少它。 您可以使用polyfill將其接近 100%,如果您仍然以 IE 為目標,我建議您這樣做。
@James 的答案是正確的,但它並不與所有瀏覽器兼容。 你可以試試這個 jQuery 解決方案:
$.get('blob:yourbloburl').then(function(data) { var blob = new Blob([data], { type: 'audio/wav' }); });
在我添加憑據之前它不起作用
fetch(url, {
headers: {
"Content-Type": "application/octet-stream",
},
credentials: 'include'
})
async function url2blob(url) { try { const data = await fetch(url); const blob = await data.blob(); await navigator.clipboard.write([ new ClipboardItem({ [blob.type]: blob }) ]); console.log("Success."); } catch (err) { console.error(err.name, err.message); } }
如果您在 package.json 中使用主頁,則 ypu 必須使用:
當前網址:http://localhost:3008/tempAppHomepageFromPackageJson/
const file: File = this.state.file;
const localUrlToFile = URL.createObjectURL(file);
const fileHash = localUrlToFile.split('/');
const objectUrl = location.href + fileHash[fileHash.length - 1];
objectUrl 是文件的本地 url。 例如,在運行時顯示您上傳的文件。
第二種解決方案是(如果您在 package.json 中沒有主頁):
const file: File = this.state.file;
const objectUrl = window.URL.createObjectURL(file);
第三種解決方案(不在 safari 中工作):
const file: File = this.state.file;
let reader = new FileReader();
reader.readAsDataURL(file);
const objectUrl = reader.result as string;
享受 ;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.