How can I obtain the absolute url (i.e. that of the server) of a file I've just uploaded please ? #4534
-
Here's my code, I want the file in my database to be saved as "https:example.com/uploads/products/product-1.jpg" and not as "product-1.jpg", what should I do? : async store({ request, response }: HttpContext) {
const data = request.all()
const payload = await createProductValidator.validate(data)
const { thumbnail } = await request.validateUsing(updateProductImageValidator)
const product = await Product.create(payload)
await thumbnail.move(app.makePath('uploads/products'))
product.thumbnail = thumbnail.fileName!
await product.save()
console.log(thumbnail.fileName!)
return response.status(201).json({ message: 'Product created !' })
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I just did this and I don't know if it's the solution: const absoluteUrl = `${env.get('APP_URL')}/uploads/products/${thumbnail.fileName}` It sends me the type of url I want but I can't see the file when I click on it, is this the right way to do it please? |
Beta Was this translation helpful? Give feedback.
-
I've just found the solution 🥳😊 1 - file ".env" : import { sep, normalize } from 'node:path'
import app from '@adonisjs/core/services/app'
const PATH_TRAVERSAL_REGEX = /(?:^|[\\/])\.\.(?:[\\/]|$)/
router.get('/uploads/*', ({ request, response }) => {
const filePath = request.param('*').join(sep)
const normalizedPath = normalize(filePath)
if (PATH_TRAVERSAL_REGEX.test(normalizedPath)) {
return response.badRequest('Malformed path')
}
const absolutePath = app.makePath('uploads', normalizedPath)
return response.download(absolutePath)
}) 3 - store : async store({ request, response }: HttpContext) {
const data = request.all()
const payload = await createProductValidator.validate(data)
const { thumbnail } = await request.validateUsing(updateProductImageValidator)
const product = await Product.create(payload)
await thumbnail.move(app.makePath('uploads/products'))
const absoluteUrl = `${env.get('APP_URL')}/uploads/products/${thumbnail.fileName}`
product.thumbnail = absoluteUrl!
await product.save()
return response.status(201).json({ message: 'Product created !' })
} |
Beta Was this translation helpful? Give feedback.
I've just found the solution 🥳😊
Here it is:
1 - file ".env" :
APP_URL=http://localhost:8000
2 - router.ts
3 - store :