如何将HTMLAudioElement音频文件上传到节点服务器?

时间:2020-10-23 19:20:22

标签: javascript node.js

我当前正在使用外部URL播放音频文件:

=VLOOKUP(A1, B:C, 2, 1)

如何以编程方式将此文件上传到节点服务器? (因此mp3文件可以存储在服务器中)

我应该使用const url = 'http://s5.qhres.com/static/465f1f953f1e6ff2.mp3'; const audio = new Audio(url); audio.play(); 获取音频数据并将其发送到服务器吗?

一些指导将不胜感激。

1 个答案:

答案 0 :(得分:1)

这是您实现上传功能以上传音频文件的方式

  • 首先我们下载文件,将其转换为二进制文件
  • 我们上传的第二秒

对于nodejs的后端,您可以使用带有Express的multer来设置和上传API,这样您就可以收到guide的文件了,可以为您提供帮助

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>