{"name":"@eggjs/multipart","version":"5.0.2-beta.19","keywords":["egg","egg-plugin","eggPlugin","multipart"],"author":{"name":"gxcsoccer","email":"gxcsoccer@126.com"},"license":"MIT","_id":"@eggjs/multipart@5.0.2-beta.19","maintainers":[{"name":"gxkl","email":"gxkl203@gmail.com"},{"name":"eggjs-admin","email":"fengmk2+eggjs@gmail.com"},{"name":"fengmk2","email":"fengmk2@gmail.com"},{"name":"atian25","email":"atian25@qq.com"},{"name":"hyj1991","email":"yeekwanvong@gmail.com"},{"name":"killagu","email":"killa07071201@gmail.com"},{"name":"coolme200","email":"2001-wms@163.com"},{"name":"akitasummer","email":"644171127@qq.com"},{"name":"niania","email":"ljracm@gmail.com"}],"homepage":"https://github.com/eggjs/egg/tree/next/plugins/multipart#readme","bugs":{"url":"https://github.com/eggjs/egg/issues"},"dist":{"shasum":"32dd125fcd8f0e1c221feb9da7421d57daeb3b6f","tarball":"http://registry-npm.ywwl.com/@eggjs/multipart/download/@eggjs/multipart-5.0.2-beta.19.tgz","fileCount":23,"integrity":"sha512-myg4ZMaSqXOW56MOHSHqUki3eWVLUJGtqUVmqv3GsX4Y6ky0cWfuQRkZ5+53eERdqXyKMlDo/l0McAXdlDXjUA==","signatures":[{"sig":"MEUCIQDFcd+U6bsqElFXK3yZoyCn5ciKGGlP9YnagUtFwNGymQIgbXSK5RrdLjFDuzGDiMLkfEuUs7R6zd0FgdAhxBPxGQs=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@eggjs%2fmultipart@5.0.2-beta.19","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":38472,"size":11388,"noattachment":false,"key":"/@eggjs/multipart/-/@eggjs/multipart-5.0.2-beta.19.tgz"},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","module":"./dist/index.js","engines":{"node":">= 22.18.0"},"exports":{".":"./dist/index.js","./app":"./dist/app.js","./types":"./dist/types.js","./lib/utils":"./dist/lib/utils.js","./package.json":"./package.json","./lib/LimitError":"./dist/lib/LimitError.js","./app/extend/context":"./dist/app/extend/context.js","./config/config.default":"./dist/config/config.default.js","./app/middleware/multipart":"./dist/app/middleware/multipart.js","./app/schedule/clean_tmpdir":"./dist/app/schedule/clean_tmpdir.js","./lib/MultipartFileTooLargeError":"./dist/lib/MultipartFileTooLargeError.js"},"gitHead":"10479c34f9434560d7d7c2fbb08f7cc226f41d2f","scripts":{"typecheck":"tsgo --noEmit"},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"oidc:4e578ddd-2328-4c11-b1de-4de77cc2d7bd"}},"repository":{"url":"git+https://github.com/eggjs/egg.git","type":"git","directory":"plugins/multipart"},"_npmVersion":"11.13.0","description":"Multipart plugin for egg","directories":{},"_nodeVersion":"24.17.0","dependencies":{"bytes":"^3.1.2","dayjs":"^1.11.13","co-busboy":"^2.0.1","@eggjs/path-matching":"3.0.2-beta.19"},"publishConfig":{"access":"public","exports":{".":"./dist/index.js","./app":"./dist/app.js","./types":"./dist/types.js","./lib/utils":"./dist/lib/utils.js","./package.json":"./package.json","./lib/LimitError":"./dist/lib/LimitError.js","./app/extend/context":"./dist/app/extend/context.js","./config/config.default":"./dist/config/config.default.js","./app/middleware/multipart":"./dist/app/middleware/multipart.js","./app/schedule/clean_tmpdir":"./dist/app/schedule/clean_tmpdir.js","./lib/MultipartFileTooLargeError":"./dist/lib/MultipartFileTooLargeError.js"}},"_hasShrinkwrap":false,"readmeFilename":"README.md","devDependencies":{"egg":"4.1.2-beta.19","urllib":"^4.8.2","formstream":"^1.5.1","is-type-of":"^2.2.0","typescript":"^5.9.3","@eggjs/mock":"7.0.2-beta.19","@types/node":"^24.10.2","@types/bytes":"^3.1.5","@eggjs/schedule":"6.0.2-beta.19","stream-wormhole":"^2.0.1"},"peerDependencies":{"egg":"4.1.2-beta.19"},"_npmOperationalInternal":{"tmp":"tmp/multipart_5.0.2-beta.19_1782699936406_0.07997492495585523","host":"s3://npm-registry-packages-npm-production"},"readme":"# @eggjs/multipart\n\n[![NPM version][npm-image]][npm-url]\n[![Known Vulnerabilities][snyk-image]][snyk-url]\n[![npm download][download-image]][download-url]\n[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://makeapullrequest.com)\n![CodeRabbit Pull Request Reviews](https://img.shields.io/coderabbit/prs/github/eggjs/multipart)\n\n[npm-image]: https://img.shields.io/npm/v/@eggjs/multipart.svg?style=flat-square\n[npm-url]: https://npmjs.org/package/@eggjs/multipart\n[snyk-image]: https://snyk.io/test/npm/@eggjs/multipart/badge.svg?style=flat-square\n[snyk-url]: https://snyk.io/test/npm/@eggjs/multipart\n[download-image]: https://img.shields.io/npm/dm/@eggjs/multipart.svg?style=flat-square\n[download-url]: https://npmjs.org/package/@eggjs/multipart\n\nUse [co-busboy](https://github.com/cojs/busboy) to upload file by streaming and\nprocess it without save to disk(using the `stream` mode).\n\nJust use `ctx.multipart()` to got file stream, then pass to image processing module such as `gm` or upload to cloud storage such as `oss`.\n\n## Whitelist of file extensions\n\nFor security, if uploading file extension is not in white list, will response as `400 Bad request`.\n\nDefault Whitelist:\n\n```js\nconst whitelist = [\n  // images\n  '.jpg',\n  '.jpeg', // image/jpeg\n  '.png', // image/png, image/x-png\n  '.gif', // image/gif\n  '.bmp', // image/bmp\n  '.wbmp', // image/vnd.wap.wbmp\n  '.webp',\n  '.tif',\n  '.psd',\n  // text\n  '.svg',\n  '.js',\n  '.jsx',\n  '.json',\n  '.css',\n  '.less',\n  '.html',\n  '.htm',\n  '.xml',\n  // tar\n  '.zip',\n  '.gz',\n  '.tgz',\n  '.gzip',\n  // video\n  '.mp3',\n  '.mp4',\n  '.avi',\n];\n```\n\n### fileSize\n\nThe default fileSize that multipart can accept is `10mb`. if you upload a large file, you should specify this config.\n\n```js\n// config/config.default.js\nexports.multipart = {\n  fileSize: '50mb',\n};\n```\n\n### Custom Config\n\nDeveloper can custom additional file extensions:\n\n```js\n// config/config.default.js\nexports.multipart = {\n  // will append to whilelist\n  fileExtensions: ['.foo', '.apk'],\n};\n```\n\nCan also **override** built-in whitelist, such as only allow png:\n\n```js\n// config/config.default.js\nexports.multipart = {\n  whitelist: ['.png'],\n};\n```\n\nOr by function：\n\n```js\nexports.multipart = {\n  whitelist: (filename) => ['.png'].includes(path.extname(filename) || ''),\n};\n```\n\n**Note: if define `whitelist`, then `fileExtensions` will be ignored.**\n\n## Examples\n\nMore examples please follow:\n\n- [Handle multipart request in `stream` mode](https://github.com/eggjs/examples/tree/master/multipart)\n- [Handle multipart request in `file` mode](https://github.com/eggjs/examples/tree/master/multipart-file-mode)\n\n## `file` mode: the easy way\n\nIf you don't know the [Node.js Stream](https://nodejs.org/dist/latest-v18.x/docs/api/stream.html) work,\nmaybe you should use the `file` mode to get started.\n\nThe usage very similar to [bodyParser](https://eggjs.org/en/basics/controller.html#body).\n\n- `ctx.request.body`: Get all the multipart fields and values, except `file`.\n- `ctx.request.files`: Contains all `file` from the multipart request, it's an Array object.\n\n**WARNING: you should remove the temporary upload files after you use it**,\nthe `async ctx.cleanupRequestFiles()` method will be very helpful.\n\n### Enable `file` mode on config\n\nYou need to set `config.multipart.mode = 'file'` to enable `file` mode:\n\n```js\n// config/config.default.js\nexports.multipart = {\n  mode: 'file',\n};\n```\n\nAfter `file` mode enable, egg will remove the old temporary files(don't include today's files) on `04:30 AM` every day by default.\n\n```js\nconfig.multipart = {\n  mode: 'file',\n  tmpdir: path.join(os.tmpdir(), 'egg-multipart-tmp', appInfo.name),\n  cleanSchedule: {\n    // run tmpdir clean job on every day 04:30 am\n    // cron style see https://github.com/eggjs/egg-schedule#cron-style-scheduling\n    cron: '0 30 4 * * *',\n    disable: false,\n  },\n};\n```\n\nDefault will use the last field which has same name, if need the all fields value, please set `allowArrayField` in config.\n\n```js\n// config/config.default.js\nexports.multipart = {\n  mode: 'file',\n  allowArrayField: true,\n};\n```\n\n### Upload One File\n\n```html\n<form method=\"POST\" action=\"/upload?_csrf={{ ctx.csrf | safe }}\" enctype=\"multipart/form-data\">\n  title: <input name=\"title\" /> file: <input name=\"file\" type=\"file\" />\n  <button type=\"submit\">Upload</button>\n</form>\n```\n\nController which hanlder `POST /upload`:\n\n```js\n// app/controller/upload.js\nconst Controller = require('egg').Controller;\nconst fs = require('mz/fs');\n\nmodule.exports = class extends Controller {\n  async upload() {\n    const { ctx } = this;\n    const file = ctx.request.files[0];\n    const name = 'egg-multipart-test/' + path.basename(file.filename);\n    let result;\n    try {\n      // process file or upload to cloud storage\n      result = await ctx.oss.put(name, file.filepath);\n    } finally {\n      // remove tmp files and don't block the request's response\n      // cleanupRequestFiles won't throw error even remove file io error happen\n      ctx.cleanupRequestFiles();\n      // remove tmp files before send response\n      // await ctx.cleanupRequestFiles();\n    }\n\n    ctx.body = {\n      url: result.url,\n      // get all field values\n      requestBody: ctx.request.body,\n    };\n  }\n};\n```\n\n### Upload Multiple Files\n\n```html\n<form method=\"POST\" action=\"/upload?_csrf={{ ctx.csrf | safe }}\" enctype=\"multipart/form-data\">\n  title: <input name=\"title\" /> file1: <input name=\"file1\" type=\"file\" /> file2: <input name=\"file2\" type=\"file\" />\n  <button type=\"submit\">Upload</button>\n</form>\n```\n\nController which hanlder `POST /upload`:\n\n```js\n// app/controller/upload.js\nconst Controller = require('egg').Controller;\nconst fs = require('mz/fs');\n\nmodule.exports = class extends Controller {\n  async upload() {\n    const { ctx } = this;\n    console.log(ctx.request.body);\n    console.log('got %d files', ctx.request.files.length);\n    for (const file of ctx.request.files) {\n      console.log('field: ' + file.fieldname);\n      console.log('filename: ' + file.filename);\n      console.log('encoding: ' + file.encoding);\n      console.log('mime: ' + file.mime);\n      console.log('tmp filepath: ' + file.filepath);\n      let result;\n      try {\n        // process file or upload to cloud storage\n        result = await ctx.oss.put('egg-multipart-test/' + file.filename, file.filepath);\n      } finally {\n        // remove tmp files and don't block the request's response\n        // cleanupRequestFiles won't throw error even remove file io error happen\n        ctx.cleanupRequestFiles([file]);\n      }\n      console.log(result);\n    }\n  }\n};\n```\n\n## `stream` mode: the hard way\n\nIf you're well-known about know the Node.js Stream work, you should use the `stream` mode.\n\n### Use with `for await...of`\n\n```html\n<form method=\"POST\" action=\"/upload?_csrf={{ ctx.csrf | safe }}\" enctype=\"multipart/form-data\">\n  title: <input name=\"title\" /> file1: <input name=\"file1\" type=\"file\" /> file2: <input name=\"file2\" type=\"file\" />\n  <button type=\"submit\">Upload</button>\n</form>\n```\n\nController which hanlder `POST /upload`:\n\n```js\n// app/controller/upload.js\nconst { Controller } = require('egg');\nconst fs = require('fs');\nconst stream = require('stream');\nconst util = require('util');\nconst { randomUUID } = require('crypto');\nconst pipeline = util.promisify(stream.pipeline);\n\nmodule.exports = class UploadController extends Controller {\n  async upload() {\n    const parts = this.ctx.multipart();\n    const fields = {};\n    const files = {};\n\n    for await (const part of parts) {\n      if (Array.isArray(part)) {\n        // fields\n        console.log('field: ' + part[0]);\n        console.log('value: ' + part[1]);\n      } else {\n        // otherwise, it's a stream\n        const { filename, fieldname, encoding, mime } = part;\n\n        console.log('field: ' + fieldname);\n        console.log('filename: ' + filename);\n        console.log('encoding: ' + encoding);\n        console.log('mime: ' + mime);\n\n        // how to handler?\n        // 1. save to tmpdir with pipeline\n        // 2. or send to oss\n        // 3. or just consume it with another for await\n\n        // WARNING: You should almost never use the origin filename as it could contain malicious input.\n        const targetPath = path.join(os.tmpdir(), randomUUID() + path.extname(filename));\n        await pipeline(part, createWriteStream(targetPath)); // use `pipeline` not `pipe`\n      }\n    }\n\n    this.ctx.body = 'ok';\n  }\n};\n```\n\n### Upload One File (DEPRECATED)\n\nYou can got upload stream by `ctx.getFileStream*()`.\n\n```html\n<form method=\"POST\" action=\"/upload?_csrf={{ ctx.csrf | safe }}\" enctype=\"multipart/form-data\">\n  title: <input name=\"title\" /> file: <input name=\"file\" type=\"file\" />\n  <button type=\"submit\">Upload</button>\n</form>\n```\n\nController which handler `POST /upload`:\n\n```js\n// app/controller/upload.js\nconst path = require('node:path');\nconst { sendToWormhole } = require('stream-wormhole');\nconst { Controller } = require('egg');\n\nmodule.exports = class extends Controller {\n  async upload() {\n    const { ctx } = this;\n    // file not exists will response 400 error\n    const stream = await ctx.getFileStream();\n    const name = 'egg-multipart-test/' + path.basename(stream.filename);\n    // process file or upload to cloud storage\n    const result = await ctx.oss.put(name, stream);\n\n    ctx.body = {\n      url: result.url,\n      // process form fields by `stream.fields`\n      fields: stream.fields,\n    };\n  }\n\n  async uploadNotRequiredFile() {\n    const { ctx } = this;\n    // file not required\n    const stream = await ctx.getFileStream({ requireFile: false });\n    let result;\n    if (stream.filename) {\n      const name = 'egg-multipart-test/' + path.basename(stream.filename);\n      // process file or upload to cloud storage\n      const result = await ctx.oss.put(name, stream);\n    } else {\n      // must consume the empty stream\n      await sendToWormhole(stream);\n    }\n\n    ctx.body = {\n      url: result && result.url,\n      // process form fields by `stream.fields`\n      fields: stream.fields,\n    };\n  }\n};\n```\n\n### Upload Multiple Files (DEPRECATED)\n\n```html\n<form method=\"POST\" action=\"/upload?_csrf={{ ctx.csrf | safe }}\" enctype=\"multipart/form-data\">\n  title: <input name=\"title\" /> file1: <input name=\"file1\" type=\"file\" /> file2: <input name=\"file2\" type=\"file\" />\n  <button type=\"submit\">Upload</button>\n</form>\n```\n\nController which hanlder `POST /upload`:\n\n```js\n// app/controller/upload.js\nconst Controller = require('egg').Controller;\n\nmodule.exports = class extends Controller {\n  async upload() {\n    const { ctx } = this;\n    const parts = ctx.multipart();\n    let part;\n    while ((part = await parts()) != null) {\n      if (part.length) {\n        // arrays are busboy fields\n        console.log('field: ' + part[0]);\n        console.log('value: ' + part[1]);\n        console.log('valueTruncated: ' + part[2]);\n        console.log('fieldnameTruncated: ' + part[3]);\n      } else {\n        if (!part.filename) {\n          // user click `upload` before choose a file,\n          // `part` will be file stream, but `part.filename` is empty\n          // must handler this, such as log error.\n          continue;\n        }\n        // otherwise, it's a stream\n        console.log('field: ' + part.fieldname);\n        console.log('filename: ' + part.filename);\n        console.log('encoding: ' + part.encoding);\n        console.log('mime: ' + part.mime);\n        const result = await ctx.oss.put('egg-multipart-test/' + part.filename, part);\n        console.log(result);\n      }\n    }\n    console.log('and we are done parsing the form!');\n  }\n};\n```\n\n### Support `file` and `stream` mode in the same time\n\nIf the default `mode` is `stream`, use the `fileModeMatch` options to match the request urls switch to `file` mode.\n\n```js\nconfig.multipart = {\n  mode: 'stream',\n  // let POST /upload_file request use the file mode, other requests use the stream mode.\n  fileModeMatch: /^\\/upload_file$/,\n  // or glob\n  // fileModeMatch: '/upload_file',\n};\n```\n\nNOTICE: `fileModeMatch` options only work on `stream` mode.\n\n## License\n\n[MIT](LICENSE)\n\n## Contributors\n\n[![Contributors](https://contrib.rocks/image?repo=eggjs/egg)](https://github.com/eggjs/egg/graphs/contributors)\n\nMade with [contributors-img](https://contrib.rocks).\n","publish_time":1782699936552,"_cnpm_publish_time":1782699936552,"dist-tags":{"beta":"5.0.2-beta.27","latest":"5.1.0","rc":"5.0.2-rc.1"}}