Why does my download feature (created using Vue JS and Laravel) result in corrupted files?

Viewed 1035

I'm currently working on a download feature which allows users to download the files (of all types) that they've uploaded. The downloading feature works (as in the files appear in my downloads folder and the file type is registered in the image that appears next to the file name), however for some reason all of the files I've downloaded are deemed corrupted or of the wrong format.

Axios request (inside a method):

    downloadFile(file) {
        axios.get(window.routes.files.download.replace("_id_", file.id), {
            headers: {
                'Content-Type': 'multipart/form-data',
                'Accept': 'application/vnd.ms-excel'
            }
        })
            .then(function(response){
            if (!window.navigator.msSaveOrOpenBlob){
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', file.name);
                document.body.appendChild(link);
                link.click();
            }else{
                const url = window.navigator.msSaveOrOpenBlob(new Blob([response.data]),file.name);
            }
                console.log(response.data);
            })
            .catch(function(error){
                console.error(error);
                if (!!error.response) console.log(error.response);
            });
    },

Laravel route:

Route::get('files/{file}', 'FileController@downloadSomeFile')->name('files.download');

My controller:

public function downloadSomeFile($id)
{
    $downloadFile = File::find($id);
    Storage::download(str_replace('/File', '', $downloadFile->path));
}

Is there a way to fix it?

Below is an example of the message I get when I try to open the downloaded file:

enter image description here

1 Answers

You have to set a responseType in your ajax if you want to download a non text file.

downloadFile(file) {
    axios.get(window.routes.files.download.replace("_id_", file.id), {
        headers: {
            'Accept': 'application/vnd.ms-excel'
        },
        responseType: 'arraybuffer' //<-- here
    })
        .then(function(response){
        if (!window.navigator.msSaveOrOpenBlob){
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', file.name);
            document.body.appendChild(link);
            link.click();
        }else{
            const url = window.navigator.msSaveOrOpenBlob(new Blob([response.data]),file.name);
        }
            console.log(response.data);
        })
        .catch(function(error){
            console.error(error);
            if (!!error.response) console.log(error.response);
        });
},
Related