簡體   English   中英

如何將 HTMLAudioElement 音頻文件上傳到節點服務器?

[英]How to upload HTMLAudioElement audio file to node server?

我目前正在使用外部 URL 播放音頻文件:

const url = 'http://s5.qhres.com/static/465f1f953f1e6ff2.mp3';
const audio = new Audio(url);
audio.play();

如何以編程方式將此文件上傳到節點服務器? (因此mp3文件可以存儲在服務器中)

我應該獲取音頻數據並使用fetch()將其發送到服務器嗎?

一些指導將不勝感激。

這是您如何實現上傳功能來上傳您的音頻文件

  • 首先我們下載文件把它變成二進制文件
  • 第二次我們上傳

對於 nodejs 中的后端,您可以使用multer和 express 來設置和上傳 API,以便您可以接收文件,這是一個可以幫助您的指南

TBN:閱讀代碼注釋,您將了解它是如何工作的

 // load status span let Status = document.getElementById("status"); // messages for status const DOWN_START = "File is being downloaded ..."; const DOWN_SUCCESS = "File is downloaded ..."; const DOWN_FAIL = "File failed to download with : "; const UPLOAD_START = "File is being Uploaded "; const UPLOAD_SUCCESS = "File is Uploaded"; const UPLOAD_FAILD = "File failed to upload with : "; // function to update status span const updateStatusMsg = (msg) => { Status.innerHTML = msg; }; // instansiate XMLHttpRequest let downloadReq = new XMLHttpRequest(); let fileUrl = null; // XMLHttpRequest Progress Listeners downloadReq.addEventListener("progress", () => updateStatusMsg(DOWN_START)); downloadReq.addEventListener("load", () => updateStatusMsg(DOWN_SUCCESS)); downloadReq.addEventListener("error", () => updateStatusMsg(DOWN_FAIL)); // Grab url from input const getUrl = (self) => { fileUrl = self.value; }; // Download File const getFile = () => { // [TIP] here i added a proxy for the app so you can have a valid cors so it can work locally downloadReq.open( "GET", "https://api.allorigins.win/get?url=" + encodeURIComponent(fileUrl), true ); downloadReq.responseType = "blob"; // Setup listener onLoad downloadReq.onload = function () { //When the file is downloaded we pass it to the upload function uploadFile(downloadReq.response); // if you want also to read the file and play it you can use this let reader = new FileReader(); reader.readAsDataURL(downloadReq.response); reader.onload = function (e) { console.log(reader); console.log("DataURL:", e.target.result); }; }; // Start Request downloadReq.send(); }; // Upload const uploadFile = (blob) => { // Create A file let audioFile = new File([blob], "audioFile"); updateStatusMsg(UPLOAD_START); // Sending Using fetch here you can add your node.js End point fetch("http://www.example.net", { method: "POST", headers: { "Content-Type": "Your Content Type", }, body: audioFile, }) .then((response) => response.json()) .then((success) => updateStatusMsg(UPLOAD_SUCCESS)) .catch((error) => updateStatusMsg(UPLOAD_FAILD + error.message)); };
 <input type="text" placeholder="Enter the file link" onchange="getUrl(this)" /> <input type="button" value="Upload File" onClick="getFile()" /> <br /> <span id="status"></span>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM