我只是想做一个简单的文件上传与强大的节点js,并与此代码:'
app.post("/upld", function(req, res){
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.filepath;
var newpath = 'uploads/' + files.filetoupload.newFilename;
fs.rename(__dirname + oldpath, __dirname + "/" + newpath, function (err) {
if (err) throw err;
res.write('File uploaded');
res.end();
});
});
});
,下面是HTML表单:
<body>
<form action="upld" method="post" enctype="multipart/form-data">
<input type="file" name="filetoupload"><br>
<input type="submit">
</form>
</body>
</html>
我得到一个错误,说没有名为"tmp/9885a1a737766e7a6963b6a00"我知道那个临时文件夹每次都会改变,那只是最近一次尝试的。
我试过通过响应发送文件数据来查看文件数据,但是那里的所有信息都检查出来了。如何从其临时文件夹访问上传的文件?
试试这个,对于oldpath,不添加__dirname,只使用oldpath:
const express = require('express');
const formidable = require('formidable');
const fs = require('fs');
const app = express();
app.get('/', (req, res) => {
res.send(`
<form action="upld" method="post" enctype="multipart/form-data">
<input type="file" name="filetoupload"><br>
<input type="submit">
</form>
`);
});
app.post("/upld", function (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.filepath;
var newpath = 'uploads/' + files.filetoupload.newFilename;
fs.rename(oldpath, __dirname + "/" + newpath, function (err) { // <<======= ONLY oldpath DO NOT ADD __dir
if (err) throw err;
res.write('File uploaded');
res.end();
});
});
});
app.listen(3000, () => {
console.log('Server listening on http://localhost:3000 ...');
});