Home > Blockchain >  Writing a image file received from request with httpserver
Writing a image file received from request with httpserver

Time:02-17

I'm sending a image from the front-end with FormData, which I get from an input type file.

I'm sending this formData to my API, and I'm trying to save it locally, When I try to open it, it doesn't show my image. I'm saving as PNG every time a file comes from the request just to try if it is getting saved properly. (I'm sending png image as well)

Any tips would be appreciated since its my first time using native http server from nodejs

Front:

    
const fileInput = document.getElementById('file')
const form = document.getElementById('form')

const handleAction = async (e) => {
    
    e.preventDefault();
    const reader = new FileReader();
    const file = fileInput.files[0]
    
    reader.readAsDataURL(file);
    reader.onloadend = (evt) => {
        fetch('http://localhost:3000', {
            method: 'POST',
            body: evt.target.result
        }).then(() => {})
    }

}

form.addEventListener('submit', handleAction)
    <!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">
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Roboto Mono:wght@300;400&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="style.css">
        <title>Upload Tests</title>
    </head>
    <body>
        <div >
            <h1>Upload de arquivo</h1>
            <form id="form" >
                <input  type="file" id="file">
                <button type="submit">Enviar</button>
            </form>
        </div>
        <script src="index.js"></script>
    </body>
    </html>

API:

    const http = require('http')
    const fs = require('fs')

    const headers = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
      };

    const reqListener = (req, res) => {
        let imagedata = ''

        res.writeHead(200, headers);

        req.on('data', (chunk) => imagedata  = chunk)
        
        req.on('end', () => {
          fs.writeFile('file.png', imagedata, 'binary', (err) => {
            if (err) throw err
            console.log('File saved!')
          })
        })
        
    }

    const server = http.createServer(reqListener)
    server.listen(3000)

CodePudding user response:

The file was coming as a base64 with some garbage before the base64 code itself.

Correct way to handle the file coming from the request is:

req.on('end', async () => {
  const base64Data = imagedata.replace(/^data:image\/(png|jpeg|jpg);base64,/,"")
  fs.writeFile('file.png', base64Data, 'base64', (err) => {
    if (err) throw err
    console.log('File saved!')
  })
})

  • Related