Skip to main content

zip photos and download from react app -


  • library: 

jszip - const zip = jszip()

file-saver - saveAs(content, `${fetchListingId}.zip`)

issue: cors - 

the original plan was download photos from the front end and zip with jszip, but got cors error when download from firebase storage

solutions:

1. on graphql, add query: getPhotosBuffer(listingId: String): [PhotoBuffer] to return stringified buffer of photos

fetchPhotosBuffer = async (listingId: string): Promise<PhotoBuffer[]> =>
this.cacheProvider.processor<PhotoBuffer[]>(
async () => {
const photos = await this.collection
.where('listingId', '==', listingId)
.orderBy('orders')
.get()

const result: PhotoBuffer[] = []
await Promise.all(
photos.docs.map(async (photo: any) => {
const data = photo.data()
const { photoUrl } = data
try {
const buffer = await axios
.get(photoUrl, {
responseType: 'arraybuffer',
})
.then(response => Buffer.from(response.data, 'binary'))

result.push({ id: photo.id, data: buffer.toString() })
} catch (err) {
console.log(err)
}
})
)

return result
},
{ key: `${this.cachePrefix}-fetchPhotos-${listingId}` }
)

2. React - parse the stringified buffer to get data

useEffect(() => {
const fetchPhotos = async () => {
const result = await client.query({
query: QUERY_LISTING_PHOTOS_BUFFER,
variables: { listingId: fetchListingId },
})

const {
data: { getPhotosBuffer },
} = result

getPhotosBuffer.forEach((photo: any) => {
zip.file(`${photo.id}.jpg`, JSON.parse(photo.data).data, {
binary: true,
})
})

zip
.generateAsync({
type: 'blob',
})
.then(content => {
saveAs(content, `${fetchListingId}.zip`)
})
.finally(() => setFetchListingId(''))
}
if (fetchListingId) {
fetchPhotos()
}
}, [fetchListingId, client, zip])

Comments

Popular posts from this blog

Online tool to remove background of images

https://www.remove.bg/upload

React way to use D3 - ( Python as API )

The Inspiration Andmap is trying to build new BI product, the tech stacks would be D3 + ReactJS as data visualization frontend, Web API, and Python provides data. As with most new projects, it didn’t take long to figure out the major roadblocks. D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation. In one of our initial discovery sessions, we realized that our application needs to be able to adapt D3 library in ReactJS way. More than that, we prefer utilizing new feature of React - Hooks. Finally, we build  component for each chart and Helpers file for drawing each chart. Here is sample for map chart: index.js: map.js - map chart container - using useEf...