首页 > 解决方案 > 如何在 Node.js 中上传和显示文件?

问题描述

我是 Node 新手,在上传文件时遇到了一些问题。我正在尝试以 text/plain 格式上传图像(jpg 和 png)和文本文件,然后在 post-route ('/upload)' 中显示它们。我已经尝试过 multer 和强大的,但无法做到正确。非常感谢一些帮助。

我尝试了所有不同类型的事件和回调,但我错过了一些关键步骤。这是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>   

这是服务器代码:

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)

我的根文件夹包含 app.js、views/index.html 和一个名为 uploads 的目录。

该代码是我的图像上传测试用例。当我运行程序时,一个具有正确名称和内容的文件会上传到目录“./uploads”中。但是,我在发布请求('/upload')的响应中看不到上传的图像。如果有人可以帮助我解决这个问题以及其他文本文件(文本/纯文本),那就太好了。干杯!

标签: node.jsfile-uploadformidable

解决方案


在请求的响应中,您可以发送值,因此 res.end(value here) 可以工作!


推荐阅读