trasherdk / hyper-express

High performance Node.js webserver with a simple-to-use API powered by uWebsockets.js under the hood.
MIT License
0 stars 0 forks source link

Snippet: Upload handler. A simplification of actual backend. #15

Open trasherdk opened 2 years ago

trasherdk commented 2 years ago
await req.multipart(async field => {
    if (!field.file) return

    const readStream = field.file.stream
    const writeStream = fs.createWriteStream('/path/to/tmp')
    readStream.pipe(writeStream)
  })

Source: https://github.com/kartikk221/hyper-express/discussions/92#discussioncomment-3147374

trasherdk commented 2 years ago

Slightly more verbose example:

app.put('/dp',(req,res)=>{
      req.multipart(
        {
          limits: { files: 1, fileSize: 2 * 1024 * 1024 },
          //@ts-ignore
          headers: req.headers,
        },
        (field) => {
          if (
            field.mime_type != "image/jpeg" &&
            field.mime_type != "image/png" &&
            field.mime_type != "image/webp" &&
            field.mime_type != "image/jiff" &&
            field.mime_type != "image/svg"
          ) {
            return res
              .status(400)
              .json({
                message: "Wrong File Submitted, Imgaes Only",
                status: false,
              });
          } [](url)
          console.log(field.truncated);
          console.log(field.file);
          console.log(field.name);
          console.log(field.encoding);
        }
      );
})

Source: https://github.com/kartikk221/hyper-express/discussions/86#discussioncomment-3113238

trasherdk commented 2 years ago

A even more verbose example, made from MultipartField documentation

HTML Code Example

<form action="https://example.com/files/upload" method="post" enctype="multipart/form-data">
    <input type="text" name="text1" value="some text value">
    <input type="text" name="text2" value="some text value">
    <input type="file" name="file1">
    <input type="file" name="file2">
    <input type="file" name="file3">
    <button type="submit">Upload</button>
</form>

Server Code Example

webserver.post('/files/upload', async (request, response) => {
    // Wrap our multipart handler in a try-catch and create a "uploaded_files" array to store temporary paths of uploaded files
    const uploaded_files = [];
    try {
          // Initiate multipart parsing
          await request.multipart(async (field) => {
                  // Check if the current field is a file-type field
                  if (field.file) {
                         // Save the file temporarily to disk with a random UUID
                         const temp_path = '/path/to/tmp-folder/' + crypto.randomUUID();
                         await field.write(temp_path);

                         // Store the file's temporary path into the "uploaded_files" array so we can do stuff with it later
                         uploaded_files.push(temp_path);
                  }
          });
    } catch (error) {
        // Send some error to the user if any occurs during multipart parsing
        return response.status(500).json({
              code: 'UPLOAD_ERROR',
              message: 'There was a problem uploading your files, please try again'
        });
    }

    // Return an error to the user if they did not upload any files
    if (uploaded_files.length == 0)
        return response.status(500).json({
              code: 'NO_FILES_UPLOADED',
              message: 'Please upload some files.'
        });

    // Do some stuff with the "uploaded_files" array here and be sure to clean up/delete any files you do not use

    // Send a success response to the user
    return response.json({
          code: 'UPLOADED'
    });
});

Source: https://github.com/kartikk221/hyper-express/discussions/45#discussioncomment-1907291