项目作者: eggjs

项目描述 :
multipart plugin for egg
高级语言: JavaScript
项目地址: git://github.com/eggjs/egg-multipart.git
创建时间: 2016-07-24T06:01:40Z
项目社区:https://github.com/eggjs/egg-multipart

开源协议:MIT License

下载


@eggjs/multipart

@eggjs/multipart"">NPM version
Node.js CI
Test coverage
@eggjs/multipart"">Known Vulnerabilities
@eggjs/multipart"">npm download
PRs Welcome
CodeRabbit Pull Request Reviews

Use co-busboy to upload file by streaming and
process it without save to disk(using the stream mode).

Just use ctx.multipart() to got file stream, then pass to image processing module such as gm or upload to cloud storage such as oss.

Whitelist of file extensions

For security, if uploading file extension is not in white list, will response as 400 Bad request.

Default Whitelist:

  1. const whitelist = [
  2. // images
  3. '.jpg', '.jpeg', // image/jpeg
  4. '.png', // image/png, image/x-png
  5. '.gif', // image/gif
  6. '.bmp', // image/bmp
  7. '.wbmp', // image/vnd.wap.wbmp
  8. '.webp',
  9. '.tif',
  10. '.psd',
  11. // text
  12. '.svg',
  13. '.js', '.jsx',
  14. '.json',
  15. '.css', '.less',
  16. '.html', '.htm',
  17. '.xml',
  18. // tar
  19. '.zip',
  20. '.gz', '.tgz', '.gzip',
  21. // video
  22. '.mp3',
  23. '.mp4',
  24. '.avi',
  25. ];

fileSize

The default fileSize that multipart can accept is 10mb. if you upload a large file, you should specify this config.

  1. // config/config.default.js
  2. exports.multipart = {
  3. fileSize: '50mb',
  4. };

Custom Config

Developer can custom additional file extensions:

  1. // config/config.default.js
  2. exports.multipart = {
  3. // will append to whilelist
  4. fileExtensions: [
  5. '.foo',
  6. '.apk',
  7. ],
  8. };

Can also override built-in whitelist, such as only allow png:

  1. // config/config.default.js
  2. exports.multipart = {
  3. whitelist: [
  4. '.png',
  5. ],
  6. };

Or by function:

  1. exports.multipart = {
  2. whitelist: (filename) => [ '.png' ].includes(path.extname(filename) || '')
  3. };

Note: if define whitelist, then fileExtensions will be ignored.

Examples

More examples please follow:

file mode: the easy way

If you don’t know the Node.js Stream work,
maybe you should use the file mode to get started.

The usage very similar to bodyParser.

  • ctx.request.body: Get all the multipart fields and values, except file.
  • ctx.request.files: Contains all file from the multipart request, it’s an Array object.

WARNING: you should remove the temporary upload files after you use it,
the async ctx.cleanupRequestFiles() method will be very helpful.

Enable file mode on config

You need to set config.multipart.mode = 'file' to enable file mode:

  1. // config/config.default.js
  2. exports.multipart = {
  3. mode: 'file',
  4. };

After file mode enable, egg will remove the old temporary files(don’t include today’s files) on 04:30 AM every day by default.

  1. config.multipart = {
  2. mode: 'file',
  3. tmpdir: path.join(os.tmpdir(), 'egg-multipart-tmp', appInfo.name),
  4. cleanSchedule: {
  5. // run tmpdir clean job on every day 04:30 am
  6. // cron style see https://github.com/eggjs/egg-schedule#cron-style-scheduling
  7. cron: '0 30 4 * * *',
  8. disable: false,
  9. },
  10. };

Default will use the last field which has same name, if need the all fields value, please set allowArrayField in config.

  1. // config/config.default.js
  2. exports.multipart = {
  3. mode: 'file',
  4. allowArrayField: true,
  5. };

Upload One File

  1. <form method="POST" action="/upload?_csrf={{ ctx.csrf | safe }}" enctype="multipart/form-data">
  2. title: <input name="title" />
  3. file: <input name="file" type="file" />
  4. <button type="submit">Upload</button>
  5. </form>

Controller which hanlder POST /upload:

  1. // app/controller/upload.js
  2. const Controller = require('egg').Controller;
  3. const fs = require('mz/fs');
  4. module.exports = class extends Controller {
  5. async upload() {
  6. const { ctx } = this;
  7. const file = ctx.request.files[0];
  8. const name = 'egg-multipart-test/' + path.basename(file.filename);
  9. let result;
  10. try {
  11. // process file or upload to cloud storage
  12. result = await ctx.oss.put(name, file.filepath);
  13. } finally {
  14. // remove tmp files and don't block the request's response
  15. // cleanupRequestFiles won't throw error even remove file io error happen
  16. ctx.cleanupRequestFiles();
  17. // remove tmp files before send response
  18. // await ctx.cleanupRequestFiles();
  19. }
  20. ctx.body = {
  21. url: result.url,
  22. // get all field values
  23. requestBody: ctx.request.body,
  24. };
  25. }
  26. };

Upload Multiple Files

  1. <form method="POST" action="/upload?_csrf={{ ctx.csrf | safe }}" enctype="multipart/form-data">
  2. title: <input name="title" />
  3. file1: <input name="file1" type="file" />
  4. file2: <input name="file2" type="file" />
  5. <button type="submit">Upload</button>
  6. </form>

Controller which hanlder POST /upload:

  1. // app/controller/upload.js
  2. const Controller = require('egg').Controller;
  3. const fs = require('mz/fs');
  4. module.exports = class extends Controller {
  5. async upload() {
  6. const { ctx } = this;
  7. console.log(ctx.request.body);
  8. console.log('got %d files', ctx.request.files.length);
  9. for (const file of ctx.request.files) {
  10. console.log('field: ' + file.fieldname);
  11. console.log('filename: ' + file.filename);
  12. console.log('encoding: ' + file.encoding);
  13. console.log('mime: ' + file.mime);
  14. console.log('tmp filepath: ' + file.filepath);
  15. let result;
  16. try {
  17. // process file or upload to cloud storage
  18. result = await ctx.oss.put('egg-multipart-test/' + file.filename, file.filepath);
  19. } finally {
  20. // remove tmp files and don't block the request's response
  21. // cleanupRequestFiles won't throw error even remove file io error happen
  22. ctx.cleanupRequestFiles([ file ]);
  23. }
  24. console.log(result);
  25. }
  26. }
  27. };

stream mode: the hard way

If you’re well-known about know the Node.js Stream work, you should use the stream mode.

Use with for await...of

  1. <form method="POST" action="/upload?_csrf={{ ctx.csrf | safe }}" enctype="multipart/form-data">
  2. title: <input name="title" />
  3. file1: <input name="file1" type="file" />
  4. file2: <input name="file2" type="file" />
  5. <button type="submit">Upload</button>
  6. </form>

Controller which hanlder POST /upload:

  1. // app/controller/upload.js
  2. const { Controller } = require('egg');
  3. const fs = require('fs');
  4. const stream = require('stream');
  5. const util = require('util');
  6. const { randomUUID } = require('crypto');
  7. const pipeline = util.promisify(stream.pipeline);
  8. module.exports = class UploadController extends Controller {
  9. async upload() {
  10. const parts = this.ctx.multipart();
  11. const fields = {};
  12. const files = {};
  13. for await (const part of parts) {
  14. if (Array.isArray(part)) {
  15. // fields
  16. console.log('field: ' + part[0]);
  17. console.log('value: ' + part[1]);
  18. } else {
  19. // otherwise, it's a stream
  20. const { filename, fieldname, encoding, mime } = part;
  21. console.log('field: ' + fieldname);
  22. console.log('filename: ' + filename);
  23. console.log('encoding: ' + encoding);
  24. console.log('mime: ' + mime);
  25. // how to handler?
  26. // 1. save to tmpdir with pipeline
  27. // 2. or send to oss
  28. // 3. or just consume it with another for await
  29. // WARNING: You should almost never use the origin filename as it could contain malicious input.
  30. const targetPath = path.join(os.tmpdir(), randomUUID() + path.extname(filename));
  31. await pipeline(part, createWriteStream(targetPath)); // use `pipeline` not `pipe`
  32. }
  33. }
  34. this.ctx.body = 'ok';
  35. }
  36. };

Upload One File (DEPRECATED)

You can got upload stream by ctx.getFileStream*().

  1. <form method="POST" action="/upload?_csrf={{ ctx.csrf | safe }}" enctype="multipart/form-data">
  2. title: <input name="title" />
  3. file: <input name="file" type="file" />
  4. <button type="submit">Upload</button>
  5. </form>

Controller which handler POST /upload:

  1. // app/controller/upload.js
  2. const path = require('node:path');
  3. const { sendToWormhole } = require('stream-wormhole');
  4. const { Controller } = require('egg');
  5. module.exports = class extends Controller {
  6. async upload() {
  7. const { ctx } = this;
  8. // file not exists will response 400 error
  9. const stream = await ctx.getFileStream();
  10. const name = 'egg-multipart-test/' + path.basename(stream.filename);
  11. // process file or upload to cloud storage
  12. const result = await ctx.oss.put(name, stream);
  13. ctx.body = {
  14. url: result.url,
  15. // process form fields by `stream.fields`
  16. fields: stream.fields,
  17. };
  18. }
  19. async uploadNotRequiredFile() {
  20. const { ctx } = this;
  21. // file not required
  22. const stream = await ctx.getFileStream({ requireFile: false });
  23. let result;
  24. if (stream.filename) {
  25. const name = 'egg-multipart-test/' + path.basename(stream.filename);
  26. // process file or upload to cloud storage
  27. const result = await ctx.oss.put(name, stream);
  28. } else {
  29. // must consume the empty stream
  30. await sendToWormhole(stream);
  31. }
  32. ctx.body = {
  33. url: result && result.url,
  34. // process form fields by `stream.fields`
  35. fields: stream.fields,
  36. };
  37. }
  38. };

Upload Multiple Files (DEPRECATED)

  1. <form method="POST" action="/upload?_csrf={{ ctx.csrf | safe }}" enctype="multipart/form-data">
  2. title: <input name="title" />
  3. file1: <input name="file1" type="file" />
  4. file2: <input name="file2" type="file" />
  5. <button type="submit">Upload</button>
  6. </form>

Controller which hanlder POST /upload:

  1. // app/controller/upload.js
  2. const Controller = require('egg').Controller;
  3. module.exports = class extends Controller {
  4. async upload() {
  5. const { ctx } = this;
  6. const parts = ctx.multipart();
  7. let part;
  8. while ((part = await parts()) != null) {
  9. if (part.length) {
  10. // arrays are busboy fields
  11. console.log('field: ' + part[0]);
  12. console.log('value: ' + part[1]);
  13. console.log('valueTruncated: ' + part[2]);
  14. console.log('fieldnameTruncated: ' + part[3]);
  15. } else {
  16. if (!part.filename) {
  17. // user click `upload` before choose a file,
  18. // `part` will be file stream, but `part.filename` is empty
  19. // must handler this, such as log error.
  20. continue;
  21. }
  22. // otherwise, it's a stream
  23. console.log('field: ' + part.fieldname);
  24. console.log('filename: ' + part.filename);
  25. console.log('encoding: ' + part.encoding);
  26. console.log('mime: ' + part.mime);
  27. const result = await ctx.oss.put('egg-multipart-test/' + part.filename, part);
  28. console.log(result);
  29. }
  30. }
  31. console.log('and we are done parsing the form!');
  32. }
  33. };

Support file and stream mode in the same time

If the default mode is stream, use the fileModeMatch options to match the request urls switch to file mode.

  1. config.multipart = {
  2. mode: 'stream',
  3. // let POST /upload_file request use the file mode, other requests use the stream mode.
  4. fileModeMatch: /^\/upload_file$/,
  5. // or glob
  6. // fileModeMatch: '/upload_file',
  7. };

NOTICE: fileModeMatch options only work on stream mode.

License

MIT

Contributors

Contributors

Made with contributors-img.