axios download every file with txt extension Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of axios download every file with txt extension without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I try to download any file from server from the laravel , but all files are downloaded as a .txt file

enter image description here this is my javascript code :

        downloadAttachment:function (id){
        axios({
            url: '/api/user/downloadFile/'+id,
            method: 'GET',
            responseType: 'blob',
        }).then((response) => {
            let fileURL = window.URL.createObjectURL(new Blob([response.data]));
            let fileLink = document.createElement('a');
            fileLink.href = fileURL;
            fileLink.setAttribute('download', response.data.type);
            document.body.appendChild(fileLink);
            fileLink.click();
        });
    }

Laravel :

    public function downloadDocument($file)
{
    $path=$file->src;
    if(Storage::exists($path))
    {
        $file=Storage::get($path);
        $type=Storage::mimeType($path);
        $response = Response::make($file, 200);
        $response->header("Content-Type", $type);
        return $response;
    }
    abort(404);
 }

Answer

Use Storage::download instead:

public function downloadDocument($file)
{
    $path = $file->src;

    if (Storage::exists($path)) {
        return Storage::download($path);
    }

    abort(404);
 }

Here is the docs.

We are here to answer your question about axios download every file with txt extension - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji