如何获取已上传文件的文件路径以创建读取流

13 浏览
0 Comments

如何获取已上传文件的文件路径以创建读取流

我正在使用Nodejs的readStream.pipe(writeStream)。如何获取我正在上传的文件的完整路径并将其分配给createReadStream。我只获取文件名,当文件在nodejs根目录中时没有错误,但是当我从其他任何地方上传时,我会遇到错误:

events.js:183
      throw er; // 未处理的'error'事件
      ^
Error: ENOENT:没有此类文件或目录,打开'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)
  })
}

这是我的表单文件

当用户点击选择或浏览按钮时,我希望filePath包含文件上传的目录路径。

目前,filePath只获取文件名,比如nike.png,我的期望是获取"C:/Users/Esen/Documents/GitHub/filestoupload/nike.png"。

0