Skip to content
Advertisement

Download File automatically with browser that can be opened or read properly

Frontend will send a post request to Scala Play Framework API to download a file. The response header is like :

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:8000
Content-Disposition:attachment; 
filename="logo_10248191299068944166699.png"; 
filename*=utf-8'logo_10248191299068944166699.png
Content-Length:53765
Content-Type:image/png
Date:Thu, 07 Sep 2017 13:05:57 GMT
Vary:Origin

My react js code is as below:

const FileDownload = require('react-file-download')
axios(req).then(response => (response.status === 200? response : 
null)).then(res =>
        {

        FileDownload(res.data, filename)

    })

It can be downloaded automatically but the file cannot be read. For example, if I download an image, the image cannot be rendered. If I download a zip file, it cannot be extracted. I already tried React-FileDownload, FileSaver, convert the res.data into arraybuffer with the creation of 8 bit array for loop – I.Just.Cant.Make.It.Work.

When I erase the extension format from ubuntu and open it on Atom, these shows up. And from the download tab in Chrome, it stated blob:http://localhost:8000/4de5d808-67a6-4d4e-9920-24bd342664f6

�PNG


IHDRwB���gAMA���asRGB��� 
cHRMz&�����u0�`:�p��Q<bKGD�������   
pHYs.#.#x�?v�IDATx���w�e�Y����9WܹrN]]�-����0�2��,����t|
�=w�{ƹ�&����`LI��`0&I�J��j�����}��J���Pa�=W�~����ݭ��jϵ~�}��1`�|�;��֟zQj�?xz�����z�N-�^n5��$�m�:Uv��Sv�]�N��%=✾s����V��Ǜ?l����>$)��7��p�y{B]]�Ò�T��J:i�̥���+.�V5����$����u����u^�����-��%��tJ��ً�[��8��$}���UOI�{޻]v��N�3k׉�I�!�+$}�����I'���cW���_sNF�DҏI�Ip�9��$�`��

Advertisement

Answer

I solved the problem. It lies in the POST request.

url: url + '/storage/download_file',
method: 'POST',
responseType: 'blob',   //THE KEY TO SUCCESS
headers: {
    Authorization: 'Bearer ' + token,
            Accept: 'application/json',
            'Content-Type': 'application/json'
  }

Have to add responseType: 'blob'

I changed to FileSaver to download file.

var blob = new Blob([res.data], {type: "application/octet-stream"});
FileSaver.saveAs(blob, filename)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement