partially download a file with Javascript - javascript

we're actually working on a Remote Music Library organizer using javascript and I'd like to know if there's a way to download using js the last 128bytes of an MP3 file in order to get its ID3 Tags. thanks.

You can't do that with just JavaScript. You'll need something on the server (what exactly depends on your server-side technology) to read the relevant part of the file. Then in JavaScript you can just call that server-side part.
Update 1
The HTTP protocol has support for downloading files in parts (which is what the). But of course HTTP knows nothing of MP3 files, so you'll have to know what range of the file contains the ID3 tag in your JavaScript.
Update 2
It seems way more feasible than I initially expected to download just a chunk of a URL in pure JavaScript:
xhr = new XMLHttpRequest();
xhr.open("GET", "http://<your domain>/");
xhr.setRequestHeader("Range", "bytes=-256");
xhr.send();
This requests the last 256 bytes of the remote file.
Note that of course your request is subject to the usual same-origin limitations, so you can only use it to retrieve files from the server that contains your original HTML/JavaScript.

Withouth using a server-sided programming language: no.
You could use Ajax and PHP (or any other programming language) to get the ID3 tag.
With jQuery it looks something like this:
function getInfo(func) {
$.ajax({
url: "mp3info.php?file=" + url,
dataType: "json",
ready: function(result) {
func(result);
}
});
}
And you use it like this:
getInfo(function(mp3info) {
alert(mp3info.id3);
});
Then your PHP file looks something like this:
<?php
$info = array(); //The MP3 info array
echo json_encode($info, true);
?>

Related

How can I send a file from a URL (not a file upload) to the backend with javascript?

I would like to have a button that when clicked gets a file (in this case a dynamically generated PDF) from a (predefined) URL on the same domain, and sends it to a (php) backend to be saved.
I am guessing that the best way to do this is to somehow load the file returned by the URL into a javascript variable, base64 encode it and send that to the backend with an ajax POST. Then on the backend I would base64 decode it and save it as a regular file.
Is this the right approach, or is there a better way to do it?
If this is the right approach, the part I am not sure how to do is getting the file from the URL into a variable. Once it's there, I guess I can use btoa() to base64 encode it. The other thing I am not 100% sure about is whether that will be compatible with base64_decode() in PHP for when I decode it?
Update
You say, the URL is predefined, and you don't know how to get in into a javascript variable. I guess, the URL is defined in the backend (PHP). So you could simply set/inject it in the client side code (javascript) with PHP.
Don't post the URL back from the client to the server, as there seems to be no need for that, and the URL could easily be changed by the user (security issue)!!!
So, maybe a better way would be to keep the URL on the server side, and inject it in the client page using php, without posting it back to the server.
Original answer
This answer is only appropriate if the client generates the URL and you have a secure way to verify it, as every client side input has to be treated as potential harmful user input.
In my opinion this is the absolutely right approach. Yes, you should base64 encode your variable. You could put the base64 encoded string in a json object and post this json object via ajax, or post it as plain text in your post body. Make sure to verify this as a client input!
I see no reason why btoa()/base64_decode() should not work. Base64 is platform independent.
I figured it out. It's a mix of vanilla and jQuery because the vanilla is from this article and the project I am working in already has jQuery available for $.ajax to make the POST to the backend easier.
var oReq = new XMLHttpRequest();
var fileUrl = '[URL from PHP]';
oReq.open("GET", fileUrl, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
let arrayBuffer = oReq.response; // Note: not oReq.responseText
if (arrayBuffer) {
let binaryText;
let byteArray = new Uint8Array(arrayBuffer);
for (var i = 0; i < byteArray.byteLength; i++) {
binaryText+=String.fromCharCode( byteArray[ i ] );
}
$.ajax({
type: "POST",
url: "/path/to/backend-upload",
data: {"fileData":btoa(binaryText)},
success: function(resultData){
alert("File Uploaded");
}
});
}
};
oReq.send(null);
and in the PHP backend:
file_put_contents("/path/to/destination", base64_decode($_POST['fileData']));

How can we download the dynamically generate file from server?

I want download the file from server (I knew that we can't use AJAX, and serve is Servlet) and which dynamically generate according to the parameters.
Now I have the parameters in format JSON, like:
{"limitTo":"name","searchFor":["AAA","BBB","CCC"],...}
So, how can we send the request to the server with those paraleters? Do we need create some inputs?
Thanks, I found the solution which uses dojo/request/iframe, without window.open
And the code likes :
require(["dojo/request/iframe"], function(iframe){
// cancel the last request
iframe._currentDfd = null;
iframe("something.xml", {
handleAs: "xml",
data : "your json"
}).then(function(xmldoc){
// Do something with the XML document
}, function(err){
// Handle the error condition
});
// Progress events are not supported using the iframe provider
});
And then we can see download window.
Here is an article about dojo/request/iframe

How to download a file via URL then get its name

This is for a userscript I'm making with JS+jQuery. I'm wondering if it's possible to find the filename given the URL.
It's in the form of:
http://example.org/download.php?action=download&id=1234
and then that link downloads a file such as "cat.jpg".
How do I find out what the file name is called? I don't need to actually save the file on the users computer - just need to find the name of the file.
I'm open to using any JS library - but I need to make sure that the file isn't actually saved in the users computer (or maybe it's just saved in a temp folder somewhere).
The simple thing you can do is to make HEAD request, so that you don't actually download the file but only response headers. From there you get Content-Disposition header which contains filename field.
Something like this in jQuery:
$.ajax({
type: "HEAD",
url: 'http://example.org/download.php?action=download&id=1234',
success: function(message, text, response) {
var header = response.getResponseHeader('Content-Disposition');
console.log(header);
}
});
header variable will be something like attachment; filename="image.jpg". Now it's easy to extract filename part:
var filename = header.match(/filename="(.+)"/)[1]; // image.jpg

Update XML on server without PHP

I have a problem. I have a JavaScript function which should update an XML file (btw please check if its correct):
function changename(node2){
var nodenumber = node2;
var newname = "tescik";
$.ajax({
type: "GET",
url: "config2.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('device').each(function () {
var node = $(this).find('node');
if (node.text() == nodenumber) {
var name = $(this).find('name').text(newname);
alert(name.text());
$.post(
"config2.xml",
{
name: "Bravo"
},
function(dane){
alert("Dane otrzymane: " + dane);
}
);
}
});
}
});
}
The problem now is: How to update that file on the web server? I can not install PHP server on this. There can be only a web server. Nothing else.
Please send my any instruction or materials which can help me.
You can't save anything to a server without any server side technology. Either you use PHP, ASP.NET or any similar server side technology or leave it.
There must be a service on the other side dictating what to do with the file it receives. You can't just copy the file over there (if you want to, use FTP or something like that)
Just realize what it will mean if this is possible:
What if I could just change a file on your webserver. Would you like that? No, of course not! At least there must be some authorization, authentication, and some software that tells where to place the file.
That is not possible. If the server does not provide some server-side way to update a file, then you can’t do it.
Imagine if a simple JavaScript file that is executed on the client’s machine could modify files on the server. That would be highly insecure. Instead, you will need at least something that processes this change on the server itself. And it’s really recommended to add some validation there too, so that one cannot just store anything (for example malicious code).

Jquery Ajax doesnt work

I have the following div in my html
<div class="result">loading</div>
And my javascript is as follows.
$(document).ready(function() {
$.ajax({
accept: 'application/rss+xml',
url: 'http://www.madhyamam.com/taxonomy/term/19/rss.xml',
success: function(data) {
$('.result').html(data);
}
});
});
But for some reasons.. it doesnt seems to work.
In jsfiddle
XML returned(firebug):
XML Parsing Error: no element found Location:
moz-nullprincipal:{9ec69805-af82-4f95-979a-f8e68d415124} Line Number
1, Column 1:
^
Solution
*I bye-passed the problem using yahoo pipe. And it worked fine.*
You can't make Ajax requests to URLs that have not the same domain, port and protocol as the current page. The Same Origin Policy forbids it.
The most common workaround is having a server-side script that pulls the content, and serves it through Ajax.
As Pekka mentioned, we guess your problem is that Ajax cannot make request on other domain URLs. You have to use server-side script for that.
Example of small php server-side script for testing (from Jquery Minime Feed library):
<?php
header('Content-type: text/xml; charset=utf-8');
$url = htmlspecialchars($_GET['url']);
echo file_get_contents('http://'.$url,0);
?>
Then you can call something like
$.ajax({
accept: 'application/rss+xml',
url: 'http://youserver/getfeed.php?url=http://www.madhyamam.com/taxonomy/term/19/rss.xml',
});
However, it seems you want to show rss feed in your page. I went to same issue and ended using Jquery Minime Feed library, which help you doing the job:
$('#test1').minimeFeed('http://index.hu/24ora/rss/');
Automatically use server-side script if needed, and produce quite nice output. See demo here

Categories

Resources