40 lines
1.2 KiB
JavaScript
40 lines
1.2 KiB
JavaScript
const fs = require('fs-extra')
|
|
const path = require('path')
|
|
const axios = require('axios')
|
|
|
|
const EXT_BY_CONTENT_TYPE = {
|
|
'image/png': '.png',
|
|
'image/webp': '.webp',
|
|
'image/gif': '.gif',
|
|
'image/jpeg': '.jpg',
|
|
}
|
|
|
|
/**
|
|
* Downloads a remote image and stores it under storage/profiles, the same
|
|
* directory setProfileImageController.js already uses for avatar uploads.
|
|
* Returns the relative "/profiles/<file>" path expected on UserModel.profile_image.
|
|
*/
|
|
async function downloadImageToProfiles(url, baseName) {
|
|
const uploadDir = path.join(__dirname, '../storage/profiles')
|
|
if (!fs.existsSync(uploadDir)) {
|
|
fs.mkdirSync(uploadDir, { recursive: true })
|
|
}
|
|
|
|
const response = await axios.get(url, {
|
|
responseType: 'arraybuffer',
|
|
timeout: 10000,
|
|
})
|
|
|
|
const contentType = String(response.headers['content-type'] || '').split(';')[0].trim()
|
|
const ext = EXT_BY_CONTENT_TYPE[contentType] || '.jpg'
|
|
const safeBaseName = String(baseName || 'user').replace(/[^\w.\-]/g, '_')
|
|
const uniqueFileName = `${safeBaseName}-${Date.now()}${ext}`
|
|
const filePath = path.join(uploadDir, uniqueFileName)
|
|
|
|
await fs.writeFile(filePath, Buffer.from(response.data))
|
|
|
|
return `/profiles/${uniqueFileName}`
|
|
}
|
|
|
|
module.exports = { downloadImageToProfiles }
|