简体   繁体   中英

How to upload and display a file in Node.js?

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!

在请求的响应中,您可以发送值,所以类似res.end(value here)的东西可以工作!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM