Am trying to download a file from a url. If I manually download and unzip it works fine, however, using download.file the zip is corrupt. I wonder if it is something to do with manually specifying the file name. Why is this neccesary when using the download.file function? Is it not possible to simply specify a url and folder and it download the file as it is named on the server?
##using R
##download url
url <- 'https://www.eea.europa.eu/data-and-maps/data/eea-reference-grids-2/gis-files/denmark-shapefile/at_download/file'
download.file(url, destfile ='Denmark_shapefile.zip')
unzip(zipfile = 'Denmark_shapefile.zip', exdir = '.')
Unzip fails as the file is corrupt
CodePudding user response:
destfile ='Denmark_shapefile.zip'
is only specifying the name the downloaded file should have. You can write anything you want in there.
Your code works for me exactly as it is, but you could try using this download statement instead of yours which is specified for writing and is binary safe.
download.file(url, destfile ='Denmark_shapefile.zip', mode='wb', cacheOK=FALSE)
CodePudding user response:
One way to do is,
url <- 'https://www.eea.europa.eu/data-and-maps/data/eea-reference-grids-2/gis-
files/denmark-shapefile/at_download/file'
Your working directory is were files are downloaded
library(stringr)
fold = str_replace_all(getwd(), '/', '\\\\')
A random file name is assigned to zip file.
fil = tempfile(pattern = "file", tmpdir = fold, fileext = '.zip')
download.file(url, fil, mode = 'wb')