简体   繁体   中英

Javascript: getting Audio via POST

I may be coming at this from completely the wrong angle (if this is the case then please feel free to tell me so) but....

I have a music app in which a user can upload a music track and then later on preview it.

The directory where the audio is stored is protected with .htaccess to prevent unauthorised access:

deny from all

Protecting this directory obviously prevents the files being accessed by Javascript:

var track = new Audio('path/to/file');

I want to be able to validate the user and then return the track through another script by passing extra info with the request for the page (too much data for a GET request).

var track = new Audio('path/to/script/to/return/audio');

Is this possible? Pretty sure it's not so if you can think of a solution, I'd be keen to hear.

Why don't you serve your audio file via a php script that would

  1. check user credentials and
  2. stream the data using the right Mime Type ?

Something like (inspired by php output file on disk to browser SO question)

in get-audio.php file

<?php 
// check user credentials
if($_GET['auth_token'] != '12345') exit;

// read the audio file
$name = $_GET['path'];
if (file_exists($name)) {

    // send the right headers
    header("Content-Type: audio/mp3");
    header("Content-Length: " . filesize($name));

    // dump the file and stop the script
    readfile($name)
    exit
}

And then, in javascript :

var track = new Audio('get-audio.php?auth_token=12345&path=path/to/file');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM