所以我在本地机器上工作,我能够将文件从路径A上传到B。
以下代码
HTML
<form action="/fileupload" method="post" enctype="multipart/form-data">
<input type="hidden" class="form-control" name="csrfmiddlewaretoken" value="{{_csrf}}">
<input type="file" name="filetoupload"><br>
<input type="submit">
</form>
的NodeJS
app.post('/fileupload', function (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = 'C:/Users/MyName/uploadtesterFile/' + files.filetoupload.name;
fs.rename(oldpath, newpath, function (err) {
console.log(err);
if (err) throw err;
res.redirect(req.get('referer'));
});
});
})
将文件上传到C:/ Users / MyName / uploadtesterFile / successfully 但当我将其更改为远程服务器路径时,它会返回错误,不允许跨设备链接以及某些内容......等等。
有没有参考?我正在学习W3Cschool教程。
答案 0 :(得分:1)
有一个名为multer的包。它是一个中间件,可以处理多部分表单并轻松上传数据。它也可以根据我们的需要进行配置。
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})
var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
// req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
//
// e.g.
// req.files['avatar'][0] -> File
// req.files['gallery'] -> Array
//
// req.body will contain the text fields, if there were any
})