This is my javascript request:
var XHR = new XMLHttpRequest();
XHR.responseType = 'blob';
XHR.addEventListener('readystatechange', function() {
if (XHR.readyState == 4) {
if (XHR.status == 200) {
var blob = new Blob([XHR.response], {type: "application/mp3"});
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = 'Myfile.mp3';
a.click();
window.URL.revokeObjectURL(url);
} else {
document.getElementById(regidrs).innerHTML = "Error: " + XHR.responseText;
}
}
});
var FD = new FormData();
FD.append('uuid', uuid);
XHR.open('POST', '/fetch');
XHR.send(FD);
This is my module routing:
my_module/my_module.routing.yml
my_module.content:
path: '/fetch'
defaults:
_controller: '\Drupal\my_module\Controller\MyController::content'
_title: 'Hello World'
requirements:
_permission: 'access content'
And my controller:
<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\drupal_set_message;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Defines HelloController class.
*/
class MyController extends ControllerBase {
/**
* Display the markup.
*
* @return array
* Return markup array.
*/
public function content() {
...
$response= file_get_contents(....);
$file = file_save_data($response, "public://myaudiofile.mp3", FILE_EXISTS_REPLACE);
...
return [
'#type' => 'markup',
'#markup' => $response,
];
}
}
But file_get_contents returns a mp3 file, and I need to pass this mp3 to the javascript httpresponse in order to donwload it. Saving $response to a file, I have checked the file is ok.
How can I do it?