Reputation: 1
I have the following element:
<a href="/temp/8072ba11-999d-484c-b074-f9f2ce249056.xlsx" download="MyFile.xlsx"> </a>
Initiating a click event on the element causes a download to occur but the file is not renamed to MyFiles.xlsx
.
The size of the file can range from 5KB to 150MB with the same results no matter the size.
The results are the same on Chrome, Edge and Firefox.
The element is generated and programmatically clicked in a Django Python environment in the success callback of an AJAX call. The JavaScript code that generates and clicks the element is:
var link = document.createElement('a');
link.href = response.url;
link.download = dl_name;
document.body.appendChild(link);
link.click();
console.log(link);
document.body.removeChild(link);
Previous posts have suggested this behavior could happen using cross-origin but my URL is same-origin.
Here is the raw response headers from the ajax call:
HTTP/1.1 200 OK Date: Wed, 08 Jan 2025 14:48:37 GMT Server: WSGIServer/0.2 CPython/3.11.5 Content-Type: application/json X-Frame-Options: DENY Content-Length: 57 X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin
I am expecting that the name of the downloaded file gets set to the value in download attribute of the anchor tag.
I have tried an endless number of things over the past week. Too many to list and honestly they are all just a jumble in my mind by now. They range from varying the path in the href
, and even altering my approach all together to use a blob as the file link but that just resulted in a corrupted XLSX file which I also was unable to solve.
As a minimal reproduceable example, I placed the anchor tag element, as it is above in bold, as the only line in an HTML file. I ran the HTML file and manually clicked the link. I received the same behavior - no renaming of the downloaded file.
Upvotes: 0
Views: 57
Reputation: 1
While I still do not know why the download attribute on the anchor tag failed to work, I did find a way to make the download use the proper name. Perhaps someone struggling with this will find it helpful.
I used this JavaScript code to create an anchor tag with an href to the view and mimic a click to call the django view:
function download_export(url, filename, dl_name)
{
var link = document.createElement('a');
link.href = url + "?data_file=" + filename + "&dl_file=" + dl_name
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
And in the view, I had the code obtain the server file path (data_file) and the desired filename (dl_file), applied the proper header myself and returned a django file response.
if request.method == 'GET':
temp_directory = str(settings.TEMP_ROOT)
filename = request.GET.get('data_file')
file_path = temp_directory + '\\' + filename
dl_file = request.GET.get('dl_file')
response = FileResponse(open(file_path, 'rb'))
response['Content-Disposition'] = f'attachment; filename="{dl_file}"'
return response
Upvotes: 0