node-formidable / formidable

The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem. Used in production.
MIT License
7.04k stars 682 forks source link

fileWriteStreamHandler: S3 access req data and other form values #848

Closed leopucci closed 2 years ago

leopucci commented 2 years ago

Hi, About store-files-on-s3.js in the example folder, How can I access req inside uploadStream Why? to get the bucket name on req. To get the path/key to destination. How can I access req info or send more data to uploadStream function? Thanks


const uploadStream = (file) => {
  const pass = new PassThrough();
  s3Client.upload(
    {
      Bucket: 'demo-bucket',
      Key: file.newFilename,
      Body: pass,
    },
    (err, data) => {
      console.log(err, data);
    },
  );

  return pass;
};

const server = http.createServer((req, res) => {
  if (req.url === '/api/upload' && req.method.toLowerCase() === 'post') {
    // parse a file upload
    const form = formidable({
      fileWriteStreamHandler: uploadStream,
    });

    form.parse(req, () => {
      res.writeHead(200);
      res.end();
    });

    return;
  }
GrosSacASac commented 2 years ago

Use a closure or the .bind method.

const uploadStream = (req, file) => {
  // req available
  const pass = new PassThrough();
  s3Client.upload(
    {
      Bucket: 'demo-bucket',
      Key: file.newFilename,
      Body: pass,
    },
    (err, data) => {
      console.log(err, data);
    },
  );

  return pass;
};

const server = http.createServer((req, res) => {
  if (req.url === '/api/upload' && req.method.toLowerCase() === 'post') {
    // parse a file upload
    const form = formidable({
      fileWriteStreamHandler: uploadStream.bind(undefined, req),
    });

    form.parse(req, () => {
      res.writeHead(200);
      res.end();
    });

    return;
  }
leopucci commented 2 years ago

Thank you @GrosSacASac