1

How can I get the filename from a given URL in PhoneGap?

In JavaScript, I used something like this:

var uri = encodeURI("http://www.openerpspain.com/descargas-documentacion?download=2");

My application downloads the file, but I have to manually set the file name. To illustrate, when I call

onclick="descarga('http://www.openerpspain.com/descargas-documentacion?download=2')"

this function is run:

function descarga(URL){
    var rutaarchivo = "file:///sdcard/data/com.protocolo/test1.pdf";
    alert(rutaarchivo);
    var filetransfer = new FileTransfer();
    filetransfer.download(URL, rutaarchivo,
        function(entry){
          alert("Download complete : " + entry.fullPath);
        },function(error) {
          alert("download error source " + error.source);
        });
}

This saves the download to ../com.protocolo, and its filename is test.pdf. I want to be able to save it as the name it is set as on the server (*manual_openerp.230209.pdf*) at the real URL, *...//www.openerpspain.com/descargas/manual_openerp.230209.pdf*.

How do I do that?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Burasuko
  • 19
  • 1
  • 4

4 Answers4

2
String fileName = url.substring(url.lastIndexOf('/') + 1);

where url is the complete path of your file.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shankar Agarwal
  • 34,573
  • 7
  • 66
  • 64
2

Use:

url="file:///sdcard/data/com.protocolo/test1.pdf?getVar=value";
url.replace(/\?.*$/,"").replace(/.*\//,"");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user2153497
  • 356
  • 2
  • 4
  • 9
0

This is basically asking How to get the file name from a full path using JavaScript?. Here, the solution was:

var filename = url.replace(/^.*[\\\/]/, '');
Community
  • 1
  • 1
Phil
  • 35,852
  • 23
  • 123
  • 164
0

I added in my URLs parameters. Then in PhoneGap I used:

function getParameterByName( name,href ){
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( href );
    if( results == null )
      return "";
    else
      return decodeURIComponent(results[1].replace(/\+/g, " "));
}

Called from :

var filename = getParameterByName ("nombrefichero", url);

So this way I can get example.pdf from:

http://www.download.com/fake/example.pdf?nombrefichero=example.pdf

And then I can download it, and save it where I want.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Burasuko
  • 19
  • 1
  • 4