Skip to content

Instantly share code, notes, and snippets.

@ibreathebsb
Last active April 5, 2023 04:43
Show Gist options
  • Star 34 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save ibreathebsb/a104a9297d5df4c8ae944a4ed149bcf1 to your computer and use it in GitHub Desktop.
Save ibreathebsb/a104a9297d5df4c8ae944a4ed149bcf1 to your computer and use it in GitHub Desktop.
file upload from dataUrl with axios
// Note: only for modern browser
import axios from 'axios'
// helper function: generate a new file from base64 String
const dataURLtoFile = (dataurl, filename) => {
const arr = dataurl.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n) {
u8arr[n - 1] = bstr.charCodeAt(n - 1)
n -= 1 // to make eslint happy
}
return new File([u8arr], filename, { type: mime })
}
// generate file from base64 string
const file = dataURLtoFile('data:image/png;base64,iVBORw0KGgoAAAANSUhEU...')
// put file into form data
const data = new FormData()
data.append('img', file, file.name)
// now upload
const config = {
headers: { 'Content-Type': 'multipart/form-data' }
}
axios.post('/path/to/upload', data, config).then(response => {
console.log(response.data)
})
@mateatslc
Copy link

consider using fetch: https://stackoverflow.com/a/36183085

@ibreathebsb
Copy link
Author

There is problem at line number 12
u8arr[n] = bstr.charCodeAt(n)

It must be
u8arr[n-1] = bstr.charCodeAt(n-1)

thanks fixed!

@Bryan03122
Copy link

I have the error "TypeError: Cannot read properties of null (reading '1')" in this line const mime = arr[0].match(/:(.*?);/)[1] . Do you know why?

@ibreathebsb
Copy link
Author

@Bryan03122 check your base64 image data,it should has a “,” in it

@nikita-fuchs
Copy link

This solution is heaven-sent ! Thank you very much !

@mscdo
Copy link

mscdo commented Apr 1, 2023

THANK YOU!!!!!!!!!! <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment