【发布时间】:2022-01-21 11:48:10
【问题描述】:
我在使用 formidable 上传文件时遇到问题。我在 Windows Server 2016 上。
我的代码完全如下所示,基于https://www.geeksforgeeks.org/how-to-upload-file-using-formidable-module-in-node-js/
const express = require('express');
const fs = require('fs');
const path = require('path')
const formidable = require('formidable');
const app = express();
app.post('/api/upload', (req, res, next) => {
const form = new formidable.IncomingForm(
{ uploadDir: __dirname + '\\tmp', keepExtensions: true }
);
form.parse(req, function(err, fields, files){
var oldPath = files.profilePic.path;
var newPath = path.join(__dirname, 'uploads')
+ '/'+files.profilePic.name
var rawData = fs.readFileSync(oldPath)
fs.writeFile(newPath, rawData, function(err){
if(err) console.log(err)
return res.send("Successfully uploaded")
})
})
});
app.listen(3000, function(err){
if(err) console.log(err)
console.log('Server listening on Port 3000');
});
我使用 Postman 发送文件。
在触发/api/upload API时,发送的文件正确放置在tmp文件夹中,但读取路径时出现问题:
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined
此消息指向fs.readFileSync(oldPath)。
console.log('files='+files) 返回files=[object Object]
console.log('files.profilePic='+files.profilePic)返回
C:\somepath\node_modules\formidable\src\PersistentFile.js:50
return `PersistentFile: ${this._file.newFilename}, Original: ${this._file.originalFilename}, Path: ${this._file.filepath}`;
^
TypeError: Cannot read properties of undefined (reading 'newFilename')
at PersistentFile.toString (C:\somepath\node_modules\formidable\src\PersistentFile.js:50:42)
所有 4 个引用的模块都存在于 node_modules 文件夹中。
【问题讨论】:
-
只是为自己尝试,但对我来说,“文件”表示某种文件数组。所以也许看看
files[0]是什么 -
以上评论不正确
标签: node.js file-upload formidable