使用 httpserver 写入从请求中接收到的图像文件

Writing a image file received from request with httpserver

我正在使用 FormData 从前端发送图像,这是我从输入类型文件中获取的。

我正在将此 formData 发送到我的 API,并尝试将其保存在本地,当我尝试打开它时,它没有显示我的图像。每次文件来自请求时,我都将其保存为 PNG,只是为了尝试它是否已正确保存。 (我也发送 png 图片)

任何提示将不胜感激,因为这是我第一次使用来自 nodejs 的本机 http 服务器

前面:

    
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 class="card-container">
            <h1>Upload de arquivo</h1>
            <form id="form" class="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)

文件以 base64 形式出现,在 base64 代码本身之前有一些垃圾。

处理来自请求的文件的正确方法是:

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!')
  })
})