我正在使用Node.js 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”
答案 0 :(得分:0)
看来您正在使用nodejs编写Express应用程序。您的问题在这里:
const readStream = fs.createReadStream(filePath);
我认为您相信这是您“读取”用户正在上传的文件的方式,但这实际上是不可能的-浏览器中不存在“ fs”模块。浏览您的网站的用户正在通过表单从计算机上载图像,这意味着图像来自HTTP请求(req
对象),而不是文件系统。
(这可能会造成混淆,因为在您的情况下,您可能正在计算机上本地运行该Express应用程序,但是在生产中更容易想象它-Express应用程序在某处的大型服务器上运行,并且与您用户的计算机上,文件将被保存在其中。)
查看相关的S.O.问题How to upload, display and save images using node.js and express。另外,请参见教程Upload Files or Images to Server using Nodejs。