Reputation: 1145
So I had it working in my local machine, I am able to upload file from path A to B.
And the code as below
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'));
});
});
})
It upload the file to C:/Users/MyName/uploadtesterFile/ successfully but when i change it to the remote server path it returns error, cross-device link not permitted and something....etc.
Is there's any reference? I am following the W3Cschool tutorial.
Upvotes: 0
Views: 1140
Reputation: 318
There is a package called as multer. It is a middleware that handles the multipart form and uploads the data easily. It is also configurable according to our need.
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
})
Upvotes: 1