Parsing binary data from request body in expressJS

Viewed 35

I am making a server to process file uploads. Here is my current front end code.

document.querySelector("form").onsubmit = e => {
  e.preventDefault();
  // Parse the file and the file extension.
  var input = document.querySelector("input"),
   files = input.files;
   
  if(files.length > 0) {
    var file = files[0];
    var ext = input.value.split("/").pop().split(".").pop();
    // Send the file to the server using fetch
    fetch("https://example.com/fileUpload", {
      method: "POST",
      headers: {
        "File-Extension": "." + ext
      },
      body: document.querySelector("input").files[0]
    })
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <form>
    Upload file<input type="file">
    <input type="submit" value="upload">
  </form>
</body>
</html>

This code sends the file extension of the file as a header, and the file contents as the body. Now on the server side, I need to process the body (which is most likely binary), and save the contents of the request body to a file with a randomly generated name ending with the file extension (supplied in the headers). I can usually use body parser for text or json, but what do I do for incoming binary data? Possibly something that returns a Buffer that contains the body?

0 Answers
Related