You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.8 KiB

  1. # express-fileupload Examples
  2. ## Basic File Upload
  3. **Your node.js code:**
  4. ```javascript
  5. const express = require('express');
  6. const fileUpload = require('express-fileupload');
  7. const app = express();
  8. // default options
  9. app.use(fileUpload());
  10. app.post('/upload', function(req, res) {
  11. let sampleFile;
  12. let uploadPath;
  13. if (!req.files || Object.keys(req.files).length === 0) {
  14. return res.status(400).send('No files were uploaded.');
  15. }
  16. // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
  17. sampleFile = req.files.sampleFile;
  18. uploadPath = __dirname + '/somewhere/on/your/server/' + sampleFile.name;
  19. // Use the mv() method to place the file somewhere on your server
  20. sampleFile.mv(uploadPath, function(err) {
  21. if (err)
  22. return res.status(500).send(err);
  23. res.send('File uploaded!');
  24. });
  25. });
  26. ```
  27. **Your HTML file upload form:**
  28. ```html
  29. <html>
  30. <body>
  31. <form ref='uploadForm'
  32. id='uploadForm'
  33. action='http://localhost:8000/upload'
  34. method='post'
  35. encType="multipart/form-data">
  36. <input type="file" name="sampleFile" />
  37. <input type='submit' value='Upload!' />
  38. </form>
  39. </body>
  40. </html>
  41. ```
  42. ## Multi-File Upload
  43. express-fileupload supports multiple file uploads at the same time.
  44. Let's say you have three files in your form, each of the inputs with the name `my_profile_pic`, `my_pet`, and `my_cover_photo`:
  45. ```html
  46. <input type="file" name="my_profile_pic" />
  47. <input type="file" name="my_pet" />
  48. <input type="file" name="my_cover_photo" />
  49. ```
  50. These uploaded files would be accessible like so:
  51. ```javascript
  52. app.post('/upload', function(req, res) {
  53. // Uploaded files:
  54. console.log(req.files.my_profile_pic.name);
  55. console.log(req.files.my_pet.name);
  56. console.log(req.files.my_cover_photo.name);
  57. });
  58. ```