Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix filepath name from remote URL in HTTP.download, fixes #696. #706

Merged
merged 1 commit into from
May 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 17 additions & 8 deletions src/download.jl
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,23 @@ function try_get_filename_from_headers(resp)
return nothing
end

function try_get_filename_from_remote_path(target)
target == "" && return nothing
filename = basename(target)
if filename == ""
try_get_filename_from_remote_path(dirname(target))
else
filename
function try_get_filename_from_request(req)
function file_from_target(t)
t == "" && return nothing
f = basename(URI(t).path) # URI(...).path to strip out e.g. query parts
return (f == "" ? file_from_target(dirname(t)) : f)
end

# First try to get file from the original request URI
oreq = req
while oreq.parent !== nothing
oreq = oreq.parent.request
end
f = file_from_target(oreq.target)
f !== nothing && return f

# Secondly try to get file from the last request URI
return file_from_target(req.target)
end


Expand All @@ -56,7 +65,7 @@ function determine_file(path, resp)
# got to to workout what file to put there
filename = something(
try_get_filename_from_headers(resp),
try_get_filename_from_remote_path(resp.request.target),
try_get_filename_from_request(resp.request),
basename(tempname()) # fallback, basically a random string
)
safer_joinpath(path, filename)
Expand Down
11 changes: 11 additions & 0 deletions test/download.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@ using HTTP
update_period=Inf)
end

@testset "filename from remote path" begin

file = HTTP.download("https://httpbingo.julialang.org/html")
@test basename(file) == "html"
file = HTTP.download("https://httpbingo.julialang.org/redirect/2")
@test basename(file) == "2"
# HTTP.jl#696
file = HTTP.download("https://httpbingo.julialang.org/html?a=b")
@test basename(file) == "html"
end

@testset "Content-Disposition" begin
invalid_content_disposition_fn = HTTP.download(
"http://test.greenbytes.de/tech/tc2231/attonlyquoted.asis")
Expand Down