在前端,影像被讀取為緩沖區,然后將其以塊的形式發送到節點服務器。下面的代碼成功執行并將影像保存到服務器。但是,當我單擊影像時,影像不可見。不知道出了什么問題,但任何幫助將不勝感激。在寫緩沖區之前我需要刪掉一些東西嗎?
"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}`));
uj5u.com熱心網友回復:
嘗試將 writeFileSync 更改為 appendFileSync。我現在正在運行您的代碼,它正在處理此更改。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/493321.html
標籤:节点.js
