[참고 사이트]Blob,Base64,File,Buffer에 대해서 설명
https://inpa.tistory.com/entry/JS-📚-Base64-Blob-ArrayBuffer-File-다루기-정말-이해하기-쉽게-설명
웹서버 → 브라우저 → 이미지 변환 → base64 url 과정을 거치기 때문에 이미지 랜더링까지 딜레이가 발생합니다.
브라우저에서는 CORS 정책으로 인해 javascript에서 fetch 메소드를 통해 데이터를 요구할 수 없습니다.
이를 해결하기 위해
//vue에서 요청할 url과 일치시키기 위해 환경변수로 관리
app.get(process.env.VITE_IMAGE_URL,async(req,res,next)=>{
try{
const baseUrlLsit = ['처리할 baseurl을 지정']
const query = req.query
if(!query.uri || !baseUrlLsit.includes(query.uri.split('/').slice(0,3).join('/'))){
return res.status(403).json(createError(403))
}
//node 18 버전 부터 fetch 함수가 추가되었습니다.
const response = await fetch(query.uri)
const blob = await response.blob()
const arrayBuffer = await blob.arrayBuffer()
res.writeHead(200,{ "Context-Type": "image/heic"})
res.write(Buffer.from(arrayBuffer))
res.end()
}
catch(error){
next(error)
}
})
express 서버에서 동일하게 fetch 함수를 사용하여 이미지를 요청합니다.
const getUrltoImage = async (url :string)=>{
const baseUrl = import.meta.env.VITE_ENVIRONMENT === 'production'? '': import.meta.env.VITE_SERVER_URL
const response = await fetch(baseUrl + import.meta.env.VITE_IMAGE_URL + `?uri=${url}`)
const blob = await response.blob()
const file = new File([blob as any],url.split('/').slice(-1)[0],{type:"image/heic"})
return file
}
import heic2any from'heic2any';
const getHeicToJpeg = async (file :File)=>{
const JpegBlob = await heic2any({
blob:file,
toType: 'image/jpeg'
})
const name = file.name.split('.')[0] + '.jpeg'
const newFile = new File([JpegBlob as any],name)
return newFile
}
npm i heic2any
const getBase64Url = async (file: File):Promise<string> =>new Promise((resolve,reject)=>{
const imageReader = new FileReader()
imageReader.onload = (e:any)=>{
if(e.target.result) resolve(e.target.result as string)
else reject("이미지 변환에 실패했습니다!")
}
imageReader.readAsDataURL(file)
})