Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
¿Cómo res.sendFile mientras res.rendering un HTML que usa el archivo enviado en Express.js?

Estoy tratando de crear un servidor de archivos que use node.js y Express. Actualmente tengo el sistema configurado para que cada usuario tenga un directorio de archivos. Actualmente lo tengo configurado para que todo el sistema de archivos esté alojado usando

 app.use(express.static(testFolder));

El problema con este enfoque es que cualquiera puede ver los archivos de cualquier persona incluso si no está conectado. He buscado y otras personas recomiendan no alojar todo el sistema de archivos y usar res.sendFile (archivo específico) en su lugar. La gente también recomienda usar middleware para verificar que el usuario esté autenticado.

Mi problema con esto es que, por ejemplo, para las fotos, tengo una ruta de fotos y un archivo EJS configurado para que, para todas las fotos, la foto que se va a ver se represente dentro del archivo .ejs.

¿Cómo res.sendFile() pero luego lo renderizo dentro de un archivo .ejs? Como solo res.sendFile() solo muestra la foto con un fondo blanco y sin personalización.

Aquí está el código de la ruta:

 router.post("/view/photo", function(req, res){ var path = req.body.currentPath var filename = req.body.fileName var currentUser = req.body.currentUser var files = fs.readdirSync(path) var images = [] var fileExtensions = ['jpg', 'jpeg', 'gif', 'png'] for(var i = 0; i < files.length; i++){ fileExtension = files[i].split(".")[1] if(fileExtension){ if(fileExtensions.includes(fileExtension.toLowerCase())){ images.push(files[i]) } } } var indexOfFile = images.indexOf(filename) var next = indexOfFile + 1; var previous = indexOfFile - 1; if(next > images.length - 1){ next = next - (images.length) } if(previous < 0){ previous = previous + (images.length) } path = path.split("/") path = path.splice(path.indexOf(currentUser, 0), path.length) path = path.join("/") finalPath = "../" + path + "/" + filename var nextFileName = images[next] var prevFileName = images[previous] res.sendFile(req.body.currentPath + "/" + filename); // res.render("showPhoto.ejs", {photoPath: finalPath, filename: filename, currentPath: req.body.currentPath, next: nextFileName, prev:prevFileName }); })
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Olvídese de reemplazar express.static con sendFile . Eso es una pista falsa.

Si desea permitir que solo los usuarios autenticados vean cualquier cosa , agregue un middleware que verifique si están autenticados en la ruta que sirve lo que sea .

No importa cómo la ruta sirva cualquier cosa , solo que autentique al usuario antes de hacerlo.

Si la ruta usa static para servir un archivo de imagen, entonces agregue algún middleware de autenticación antes. Si la ruta usa render para generar un documento HTML que incluye un <img> que apunta a la ruta estática mencionada anteriormente, entonces agregue algún middleware de autenticación antes. etc.

 router.post( "/view/photo", authenticationMiddleware, photoPostingEndpointFunction ); router.use( "/photos", authenticationMiddleware, express.static('path/to/protected/photos) );
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!