在前端,图像作为缓冲区读取,然后将其分块发送到 node 服务器.下面的代码成功执行并将图像保存到服务器.但是,当我单击图像时,图像不可见.我不知道怎么了,但我们非常感谢您的帮助.在写入缓冲区之前,是否需要删除一些内容?

"FRONTEND"

const getImageInput = document.getElementById('imageInput');


getImageInput.addEventListener('change',(event)=>{
  uploadImage(event.target.files)
 
})



function uploadImage(files){

  Array.from(files).forEach((file)=>{
    imageUploadApi(file)
  })
}


async function imageUploadApi(file){

const reader = new FileReader()

reader.readAsArrayBuffer(file)
reader.addEventListener('load',async(event)=>{

  const CHUNK_SIZE = 1000
  const chunkCount = event.target.result.byteLength / CHUNK_SIZE
  const fileName = file.name
  for(let i = 0; i < chunkCount + 1; i++){
    const chunk = event.target.result.slice(i * CHUNK_SIZE, i * CHUNK_SIZE + CHUNK_SIZE)
    const response = await fetch('http://localhost:8000/image-upload',{
      method:'POST',
      body: chunk,
      headers:{
        'Content-Type':'application/octet-stream',
        'Content-Length':chunk.length,
        'file-name': fileName
      }
    })

    console.log(await response.json())

  }

})

}
"BACKEND"

const express = require('express');
const app = express();
const cors = require('cors');
const https = require('https');
const fs = require('fs');



//BodyParser middleware
app.use(express.json());

//Setting up the cors config
app.use(cors());

app.post('/image-upload',(req,res)=>{
req.on('data',(chunk)=>{

  fs.writeFileSync(`./upload_pictures/${req.headers['file-name']}`, chunk, 'base64')
})

  res.status(200).json({
    message:'Chunk Uploaded Successfully'
  })
})


if(process.env.NODE_ENV === 'production'){

  //Set static folder
  app.use(express.static('client/build'));

  app.get('*', (req, res) =>{
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
  });
}

const port = process.env.PORT || 5000;



app.listen(port, () => console.log(`Server started on port ${port}`));

推荐答案

try 更改appendFileSync的writeFileSync.我现在正在运行你的代码,它正在处理这个变化.

Node.js相关问答推荐

promise 所有映射或反对

Sveltekit停靠的应用程序找不到从Build导入的包

NPM:无法导入本码模块

Mongoose抱怨说,整数是数字,而不是整数

一个函数中的两个依赖的NodeJS数据库操作.如果第二个失败了怎么办?

Redis Typescript 删除方法类型转换

几个 lambda 共有的函数

MongoDB:通过匹配输入字符串或输入字符串中的单个单词进行搜索

我需要聚合两个 MongoDB 集合

mongoose 7.0.3 使用运算符 $and 严格搜索日期

对 google api v3 的 Axios 请求返回加密(?)数据

Zod 模式中的self 数组

在将用作 nodejs/expressjs 中的中间件的函数中使用 keycloak.protect()

将已保存的卡片从条带显示到前端

在 Express-js 中使用路由

在 Javascript 逻辑中访问 EJS 变量

我应该在(Docker)容器中使用 forever/pm2 吗?

node.js 在控制台上显示未定义

续集findbyid不是一个函数,但显然findAll是

找不到在 docker compose 环境中运行的 node js 应用程序的模块