Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download a file keeping original filename when final link is hidden

I need to download a file, save it in a folder while keeping the original filename from the website.

url <- "http://www.seg-social.es/prdi00/idcplg?IdcService=GET_FILE&dID=187112&dDocName=197533&allowInterrupt=1"

From a web browser, if you click on that link, you get to download an excel file with this filename:

AfiliadosMuni-02-2015.xlsx

I know I can easily download it with the command download.file in R like this:

download.file(url, "test.xlsx", method = "curl")

But what I really need for my script is to download it keeping the original filename intact. I also know I can do this with curl from my console like this.

curl -O -J $"http://www.seg-social.es/prdi00/idcplg?IdcService=GET_FILE&dID=187112&dDocName=197533&allowInterrupt=1"

But, again, I need this within an R script. Is there a way similar to the one above but in R? I have looked into the RCurl package but I couldn't find a solution.

like image 633
Carlos Tafur Porras Avatar asked Mar 12 '15 18:03

Carlos Tafur Porras


1 Answers

You could always do something like:

library(httr)
library(stringr)

# alternate way to "download.file"
fil <- GET("http://www.seg-social.es/prdi00/idcplg?IdcService=GET_FILE&dID=187112&dDocName=197533&allowInterrupt=1", 
           write_disk("tmp.fil"))
# get what name the site suggests it shld be
fname <- str_match(headers(fil)$`content-disposition`, "\"(.*)\"")[2]
# rename
file.rename("tmp.fil", fname)
like image 128
hrbrmstr Avatar answered Sep 29 '22 01:09

hrbrmstr