I am trying to create a google-chrome-extension that will download an mp3 file. I am trying to use HTML5 blobs and an iframe to trigger a download, but it doesn't seem to be working. Here is my code:
var finalURL = "server1.example.com/u25561664/audio/120774.mp3";
var xhr = new XMLHttpRequest();
xhr.open("GET", finalURL, true);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();
bb.append(xhr.responseText);
var blob = bb.getBlob("application/octet-stream");
var saveas = document.createElement("iframe");
saveas.style.display = "none";
saveas.src = window.webkitURL.createObjectURL(blob);
document.body.appendChild(saveas);
delete xhr;
delete blob;
delete bb;
}
}
xhr.send();
When looked in the console, the blob is created correctly, the settings look right:
size: 15312172
type: "application/octet-stream"
However, when I try the link created by the createObjectURL(),
blob:chrome-extension://dkhkkcnjlmfnnmaobedahgcljonancbe/b6c2e829-c811-4239-bd06-8506a67cab04
I get a blank document and a warning saying
Resource interpreted as Document but
transferred with MIME type
application/octet-stream.
How can get my code to download the file correctly?
The below code worked for me in Google chrome 14.0.835.163:
var finalURL = "http://localhost/Music/123a4.mp3";
var xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/octet-stream");
//xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.open("GET", finalURL, true);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();
var res = xhr.response;
if (res){
var byteArray = new Uint8Array(res);
}
bb.append(byteArray.buffer);
var blob = bb.getBlob("application/octet-stream");
var iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = window.webkitURL.createObjectURL(blob);
document.body.appendChild(iframe);
};
xhr.send(null);
I'm not sure, but i think this is your server's trouble. I've just tried your piece of code to download some sample blob of mp3-file and everything went ok. So maybe:
this file doesn't exist on your server
you server outputs wrong mime type for mp3 files
Related
I have list of html stored in database, I want to retrieve the data and convert it to pdf and after converting download it with via ajax request.
I tried hands on it but when the pdf get download the downloaded file is empty.
Please what do i need to do?
Thank you.
JS Code
SMSLiTe('click','.export-to-pdf',function(event){
event.preventDefault();
///export note to pdf via ajax
if (typeof notes[0].note.nid !== typeof undefined && notes.length) {
var nid = notes[0].note.nid;
var fd = new FormData();
fd.append('export_to_pdf',true);
fd.append('note_id',nid);
request.open(bigPipe.formMethod.a, 'pdf/pdf');
request.send(fd);
request.onload = function(e){
if (request.readyState == request.DONE && request.status ==200) {
//code here ....download
var data = request.responseText,
blob = new Blob([data]),
a = document.createElement('a'), d = new Date();
a.href = window.URL.createObjectURL(blob);
a.download = d.getTime()+'.pdf'; a.click();
}
}
}else{
sustainScroll(bigPipe.c_w,bigPipe.class.fixed);
var msg = 'Sorry! something gone wrong, please refresh this page and try again.',title = 'Export Failed';
$(bigPipe.document).append(flexibleDialog({content:templateHTML.flexDialog(msg,title,'_2d0',null,'Close',null,0),isClass:'export_to_pdf_failed _2d0',heigt:140,width:600}));jkg();
}
});
PHP Code
if (isset($_POST['note_id'],$_POST['export_to_pdf'])) {
$nid = (int)$_POST['note_id'];
$sql = "SELECT content FROM $notes_table WHERE note_id='{$nid}' LIMIT 1";
$query = mysqli_query($conn,$sql);
if (mysqli_num_rows($query)) {
$row = mysqli_fetch_assoc($query);
$content = $row['content'];
//create PDF file
$mpdf = new mPDF();
$mpdf->WriteHTML($content);
$mpdf->Output(time().'.pdf','D');exit;
}
}
Inspecting the response data returning from MPDF I realized the output data was a blob and since the data was already blob data. I had a clue of changing the responseType of XMLHttpRequest.responseType to blob
and it worked for now.
modified JS:
SMSLiTe('click','.export-to-pdf',function(event){
event.preventDefault();
//set request method
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
} else { // code for IE6, IE5
var request = new ActiveXObject("Microsoft.XMLHTTP");
}
///export note to pdf via ajax
if (typeof notes[0].note.nid !== typeof undefined && notes.length) {
var nid = notes[0].note.nid;
var fd = new FormData();
fd.append('export_to_pdf',true);
fd.append('note_id',nid);
request.open(bigPipe.formMethod.a, 'pdf/pdf');
request.send(fd);
request.responseType = 'blob';//change reponseType before onload
request.onload = function(e){
if (request.readyState == request.DONE && request.status ==200) {
//code here ....download
var data = request.response,
blob = new Blob([data],{type: 'application/pdf'}),
a = document.createElement('a'), d = new Date();
a.href = window.URL.createObjectURL(blob);
a.download = d.getTime()+'.pdf'; a.click();
//console.log(data);
}
}
}else{
sustainScroll(bigPipe.c_w,bigPipe.class.fixed);
var msg = 'Sorry! something gone wrong, please refresh this page and try again.',title = 'Export Failed';
$(bigPipe.document).append(flexibleDialog({content:templateHTML.flexDialog(msg,title,'_2d0',null,'Close',null,0),isClass:'export_to_pdf_failed _2d0',heigt:140,width:600}));jkg();
}
});
PHP Code:
We have to output MPDF as string since we're not appending MPDF to browser;
//create PDF file
$mpdf = new mPDF();
$mpdf->WriteHTML($content);
$output = $mpdf->Output(time().'.pdf','S');//output as string
echo($output); //final result to JS as blob data
Hi I am new to java script, I am trying to download zip file from a web server running in http://10.1.2.137:5000/download.
When I access the URL alone in the browser as http://10.1.2.137:5000/download, te zip file is getting downloaded , but when I call from java script , the zip file is getting corrupted it seems. Not able to open the zip file with win rar.
Not sure this is the issue with CORS.
$scope.downloadData = function (){
console.log ('Entering in to Download Method')
var url = 'http://10.1.2.137:5000/download';
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.responseType = "arraybuffer";
var linkElement = document.createElement('iframe');
document.body.appendChild(linkElement)
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var blob = new Blob([str2bytes(xhr.response)], {type: "application/zip"});
var fileName = "logs.zip";
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display:none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
}
}
};
You can use window.open, this will instruct the browser to open the url and start download. e.g.
window.open("http://10.1.2.137:5000/download","_self");
This question already has answers here:
Download a file from Servlet using Ajax
(3 answers)
Closed 6 years ago.
How can i download XSLX or DOCX file using XMLHTTPRequest response in IE 9 ? I only need the IE 9 Solution.
This code works good for plain-text and csv Files but when i try to download XSLX or DOCX files nothing happens.
The response came from a java servlet with response-content-type set to
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
The javascript function that i need for downloading files.
function submitForm(command, event) {
disableButtons();
var form = $('form[name=myForm]');
var dataString = form.serialize();
var xhr = new XMLHttpRequest();
xhr.open('POST', myURL, true);
//tested => xhr.responseType = 'arraybuffer';
//tested => try { xhr.responseType = "arraybuffer"; } catch (e) { }; application/zip
//tested => try { xhr.responseType = "msxml-document"; } catch (e) { };
xhr.onreadystatechange = function() {
if(xhr.readyState == 4){
// xhr is complete (200 for web servers, 0 for local files in IE)
if ((xhr.status == 200)||(xhr.status == 0)){
// good
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = xhr.getResponseHeader('Content-Type');
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
var frame = document.createElement('iframe');
document.body.appendChild(frame);
frame.contentWindow.document.open(type, "replace");
frame.contentWindow.document.write(xhr.responseText); //tried also responseXML
frame.contentWindow.document.close();
frame.contentWindow.focus();
frame.contentWindow.document.execCommand('SaveAs', true, filename);
document.body.removeChild(frame);
setTimeout(function () {
URL.revokeObjectURL(downloadUrl);
}, 100); // cleanup
} else{
// error
}
}
}
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(dataString);
}
You can't, not with XMLHTTPRequest and IE9.
You can just use the form to submit the request and set its target to an iframe, the response content disposition header is set to attachment it will cause the save dialog to open.
<form name="myForm" target="somehiddeniframe>
..
</form>
I am working on an mobile App and have some issues with the jQuery AJAX get method. I want to receive a video from my server, but somehow I can't receive the file in the format I want.
Here is my code (receiving the data as blob and everything):
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'MyServerAddress/testVideos/test.mp4', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (xhr.status === 200) {
var video = document.createElement('video');
video.src = window.URL.createObjectURL(this.response);
video.autoplay = true;
document.body.appendChild(video);
}else{
"CORS failed. Check Internet Connection."
}
};
xhr.send();
But unfortunately this code doesn't run on mobile devices.
The jQuery Ajax:
jQuery.ajaxSetup({
async:false,
dataType:'blob'
});
$.get("MyServerAddress/testVideos/test.mp4",function(d){
var video = document.createElement('video');
video.src = window.URL.createObjectURL(d);
video.autoplay = true;
document.body.appendChild(video);
}).error(function(xhr, ajaxOptions, thrownError){
console.log(xhr);
console.log(ajaxOptions);
console.log(thrownError);
});
When I run the jQuery code I get the following error:
parser error (index):67 No conversion from text to blob"
Because the transmitted data isn't of the type blob.
Is there any possibility to send the data from jQuery directly as blob? If yes, how? And is there a way to make the code above work on mobile devices too?
Thank you very much,
SirSandmann
I'm looking for some way to upload video via XHR, and video convert, my script in XHR looks like.
var files= $("#camera"+id).prop('files');
var file = files[0];
var cList= files.length;
$("#camera"+id).val('');
$("#textarea"+id).val('');
var fd = new FormData();
fd.append("file", file);
fd.append("name", name);
fd.append("desc", desc);
fd.append('id', id);
var xhr = new XMLHttpRequest();
xhr.open("POST", "addUcChallenge.php", true);
xhr.upload.onprogress = function(e)
{
};
xhr.onload = function()
{
if(this.status == 200)
{
cList = 1;
//alert(xhr.responseText);
};
};
if(cList < 1)
{
}
else
{
xhr.send(fd);
}
When I tried to upload video is happen nothink, and when I wanted return some value of file nothing too, but photos are ok, and second think is that I don't know how to handle with video in PHP ( Upload, convert to flv ) Thank you!
For uploading you can use PlUploader code example (that is used for large file uploading and make sure you have edited the max file uploading size in php.ini file if you are using php in backend) and for conversion you have to use the FFMPEG