我在使用强大的上传文件时遇到问题。我在Windows服务器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');
});
我用邮差寄文件。
当触发/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:somepathnode_modulesformidablesrcPersistentFile.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:somepathnode_modulesformidablesrcPersistentFile.js:50:42)
所有4个引用的模块都存在于node_modules文件夹中。
只需更改
var oldPath = files.profilePic.path;
至
var oldPath = files.profilePic.filepath;
还要确保创建";上传";文件夹,因为代码不会创建它,没有它就会失败。
编辑:一个附带的注意事项是,如果您的环境在控制台记录对象时只是抛出[对象对象],那么可能会得到一个新的环境(visualstudio代码很好(,它会提供有用的信息。
更改var oldPath=files.profilePic.path
至
oldPath=文件.profilePic.filepath
将纠正错误