- Notifications
You must be signed in to change notification settings - Fork 1.6k
Node example
Jason Rice edited this page Jun 20, 2017 · 7 revisions
This example uses Express 4.0 and connect-multiparty (which implements Multiparty) middleware that allows access to req.files.file
Upload.upload({ url: 'api/upload', method: 'POST', data: data, // Any data needed to be submitted along with the files file: files // 1..n files });app.js
// Requires multiparty multiparty = require('connect-multiparty'), multipartyMiddleware = multiparty(), // Requires controller FileUploadController = require('./controllers/FileUploadController'); // Example endpoint router.post('/api/upload', multipartyMiddleware, FileUploadController.uploadFile);FileUploadController.js
FileUploadController = function() {}; FileUploadController.prototype.uploadFile = function(req, res) { /** * The following takes the blob uploaded to an arbitrary location with * a random file name and copies it to the specified file.path with the file.name. * Note that the file.name should come from your upload request on the client side * because when the file is selected it is paired with its name. The file.name is * not random nor is the file.path. */ fs.readFile(req.files.file.path, function (err, data) { // set the correct path for the file not the temporary one from the API: file.path = "/media/images/" + file.name; // copy the data from the req.files.file.path and paste it to file.path fs.writeFile(file.path, data, function (err) { if (err) { return console.warn(err); } console.log("The file: " + file.name + " was saved to " + file.path); }); }); } module.exports = new FileUploadController();