0

I'm new to Node and have some problems with uploading files. I'm trying to to upload images (both jpg and png) and text files in text/plain and then display them at the post-route ('/upload)'. I've tried both multer and formidable but cannot get it right. Would really appreciate some help.

I tried all different kinds of events and callbacks, but I'm missing some crucial steps. Here is the html:

<!DOCTYPE html>
  <html lang="en">
  <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial- 
     scale=1.0">
     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     <title>Testform</title>
 </head>
 <body>
   <form method="post" enctype="multipart/form-data" 
    action="/upload">
     <div>
       <input type="file" name="file" size="35">
     </div>
     <button type="submit" value="Click me" name="submit-btn">Click me</button>
   </form>
   </body>
</html>   

And here is the server code:

const formidable = require('formidable')
const express = require('express')
const path = require('path') 

const app = express()

app.get('/', (req, res) => {
   res.sendFile(path.resolve('views', 'index.html'))
})

app.post('/upload', (req, res) => {

  const form = new formidable.IncomingForm()

  form.uploadDir = __dirname + '/uploads/'

  form.parse(req)

  form.on('fileBegin', (name, file) => {
    file.path = form.uploadDir + file.name
    res.write(`<img src="./uploads/${file.name}">`)
    res.end()
  })
 })

 app.listen(3000)

My root folder contains app.js, views/index.html, and a directory called uploads.

The code is my test case for image uploads. When I run the program a file with the correct name and content get uploaded into the directory './uploads'. However, I cannot see the uploaded image in the response of the post request ('/upload'). Would be great if anyone could help me with this and also for other text files (text/plain). Cheers!

1 Answer 1

0

In the response of the request you can send values, so something like res.end(value here) works!

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but is there really a difference between doing it within 'res.write()' and 'res.end()'?
Sorry but I don’t see how this would help me in this case. It basically covers some differences between res.end() and res.send(); differences that are irrelevant here. Thanks anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.