F
F
Furamy2021-03-12 22:04:47
HTML
Furamy, 2021-03-12 22:04:47

How to download base64 encoded file?

It is necessary to implement the functionality of uploading and downloading a file, I did the upload through input type="file", but I get it in base64, and when I try to make a download link through a href="base64" download="filename.file" I get this in the console : 604bba9b8ba46431935124.png

Download functionality

fileUpload(fileInput: HTMLInputElement, type: string, attached: IAttached): void {
        fileInput.onchange = (e: Event) => {
            const { files } = e.target as HTMLInputElement

            [].forEach.call(files, (file: File) => {
                const fileReader = new FileReader()

                console.log(file)

                fileReader.onload = (ev: ProgressEvent) => {
                    const fr = ev.target as FileReader
                    console.log(fr)

                    const attach: IAttach = {
                        name: file.name,
                        type: file.type,
                        size: file.size,
                        result: fr.result
                    }

                    if (file.type.match('image'))
                        attached.images.push(attach)
                    else if (file.type.match('video'))
                        attached.videos.push(attach)
                    else
                        attached.files.push(attach)

                }

                fileReader.readAsDataURL(file)
            })
        }

        fileInput.click()
    }

<div class="attached">
      <div class="files">
        <a *ngFor="let attach of attached.files"
           [href]="attach.result"
           download="{{ attach.name }}"
        >
          <span class="name">{{ attach.name }}</span>
          <span class="size">{{ attach.size }}</span>
        </a>
      </div>
      <div class="images"></div>
      <div class="videos"></div>
    </div>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nadim Zakirov, 2021-03-13
@zkrvndm

First, convert base64 to Blob using fetch by simply downloading the file, and only then give Blob for download using URL.createObjectURL
Links to materials:
https://learn.javascript.ru/fetch
https://learn.javascript.ru/blob# 0qlrkgk6lj
PS In general, I don't understand why the hell you don't save the file somewhere before converting d base64, and only then this file can be easily downloaded using the same URL.createObjectURL

A
Anton Spirin, 2018-01-17
@rockon404

Run in the project directory in the terminal:
In the source code, import and use:

import signalR from 'signalr-client';

const client  = new signalR.client( ... );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question