night_programmer
night_programmer

Reputation: 137

JavaScript & Node - Saving Image File To Server But Unable To View

On the frontend the image is read as buffer and then sends it to node server in chunks. The code below successfully executes and saves the image to the server. However, when I click on the image, the image is not viewable. Not sure whats wrong but any help will be greatly appreciated. Is there something I need to cut out before writing the buffer?

"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}`));

Upvotes: 3

Views: 110

Answers (1)

codeRookieErick
codeRookieErick

Reputation: 36

Try to change the writeFileSync for an appendFileSync. I have your code running right now and it's working with this change.

Upvotes: 1

Related Questions