【发布时间】:2019-06-15 05:43:24
【问题描述】:
我正在使用 Nodejs readStream.pipe(writeStream)。如何获取正在上传的文件的完整路径并将其分配给 createReadStream。我只得到文件名,当文件在 nodejs 根目录中时没有错误,但是当我从其他任何地方上传时,我得到一个错误:
events.js:183
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open 'C:\Users\Esen\Documents\GitHub\gbmsturbo\nike.png'
我知道发生这种情况是因为我上传的 nike.png 不在“C:\Users\Esen\Documents\GitHub\gbmsturbo\”中。 它在这个文件夹中: "C:\Users\Esen\Documents\GitHub\filestoupload"
我试过了
function throwErrorDontCrash() {
process.on('uncaughtException', function (err) {
console.error(err.message)
})
}
这可以防止nodejs崩溃并上传文件但内容为空(0字节)
router.post('/upload', (req, res) => {
var filePath = req.body.file
var ext = path.extname(filePath)
var filename = path.basename(filePath, ext)
var newVerFilePath = "public/uploads/" + newVerFileName+ext
const readStream = fs.createReadStream(filePath)
throwErrorDontCrash()
const writeStream = fs.createWriteStream(newVerFilePath)
readStream.pipe(writeStream)
function throwErrorDontCrash() {
process.on('uncaughtException', function (err) {
//console.error(err.message)
})
}
这是我的表单文件
<form class="center" action="/upload" method="post">
<input id="file" type="file" name="file" required encrypt="multipart/form-data"/>
<input type="submit" value="UPLOAD">
我希望 filePath 包含用户单击“选择”或“浏览”按钮时上传文件的目录路径。 目前,filePath 仅获取诸如 nike.png 之类的文件名,我的期望是 获取“C:/Users/Esen/Documents/GitHub/filestoupload/nike.png”
【问题讨论】: