How to get the name of the file that the user can download?

1.7k Views Asked by At

I have a django view that returns a FileResponse

return FileResponse(protected_pdf_file, as_attachment=True, filename='result.pdf')

I am getting this response using ajax -

function ajaxSend(url, data) {
    fetch(url, {
        method: 'POST',
        body: data,
    })
        .then(response => {
            if (content_type === 'application/json') {
                return response.json();
            } else {
                return response.blob();
            }
        })
        .then(data => {
            if (data instanceof Blob) {
                const url = URL.createObjectURL(data);
                download_link.href = url;

                // download_link.download = ...

                download_link.style.display = 'block';
            } else {
                block_msg.textContent = data.message;
            }
        })
        .catch(error => console.error(error))
}

Where "download_link.download = ..." I need to substitute the file name.

I tried to get the file name - const contentDisposition = response.headers.get('Content-Disposition');, but contentDisposition is null as a result.

Please tell me how to get the name of the file returned from the server?

1

There are 1 best solutions below

0
Temi On BEST ANSWER
function ajaxSend(url, data) {
    fetch(url, {
        method: 'POST',
        body: data,
    })
        .then(response => {
            if (content_type === 'application/json') {
                return response.json();
            } else {
                const contentDisposition = response.headers.get('Content-Disposition');
                const parts = contentDisposition.split(';');
                fileName = parts[1].split('=')[1];
                return response.blob();
            }
        })
        .then(data => {
            if (data instanceof Blob) {
                // You can use fileName here

                const url = URL.createObjectURL(data);
                download_link.href = url;

                // download_link.download = ...

                download_link.style.display = 'block';
            } else {
                block_msg.textContent = data.message;
            }
        })
        .catch(error => console.error(error))
}

Also remember to set headers = {'Access-Control-Expose-Headers': 'Content-Disposition'}, and then add it to your FileResponse(protected_pdf_file, as_attachment=True, filename='result.pdf', headers=headers)