在前端,图像作为缓冲区读取,然后将其分块发送到 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}`));