node.js - 如何在 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')的响应中看不到上传的图像。如果有人可以帮助我解决这个问题以及其他文本文件(文本/纯文本),那就太好了。干杯!
解决方案
在请求的响应中,您可以发送值,因此 res.end(value here) 可以工作!
推荐阅读
- android - Firebase Firestore 回收器视图适配器复制每个文档的列表
- regex - 正则表达式匹配不确定数量的前缀
- msg - 需要 Windows 10 家庭版 msg.exe 的子程序
- angular - 尝试在生产中构建 Angular 应用程序时出现数据表错误
- angular-material - 如何将我的工作转换为材料角度/垫选择
- ios - kCVPixelFormatType_420YpCbCr8Planar 和 kCVPixelFormatType_420YpCbCr8PlanarFullRange 有什么区别?
- numpy - TypeError:不能将序列乘以“float”类型的非整数,非常感谢
- arduino-ide - 我尝试解析从 LoRa LoRa.readString() 发送的一些传感器数据
- c# - 询问用户是否想再玩一次,c#
- ruby-on-rails - 无法在页面刷新时保持会话