0

My images successfully uploaded to the /myshop/uploads/ folder, but I difficult to load images to the browser. This is my server-side code

const storage = multer.diskStorage({
            destination: (req, file, callBack) => {
            callBack(null, 'uploads')
            },
            filename: (req, file, callBack) => {
            callBack(null, Date.now() + '-'+ file.originalname)
            }
     })
    
    var upload = multer({storage: storage})
    
    
    
    //Upload image
    app.post('/api/myshop/photo', upload.single('file'),(req, res, next)=>{
    
    
            const file = req.file
            console.log(req.file.filename);
            if(!file){
            const error = new Error('Please upload a file')
            error.httpStatusCode = 400
            return next(error)
            }
    
            res.send(file)
    });

Here my folder view

1 Answer 1

1

To send the file back to the client, you can use sendFile method. You need to provide the file's path.

  //Upload image
    app.post('/api/myshop/photo', upload.single('file'),(req, res, next)=>{
    
            const file = req.file
            console.log(req.file.filename);
            if(!file){
              const error = new Error('Please upload a file')
              error.httpStatusCode = 400
              return next(error)
            }
    
            // send file back to client
            const filePath = req.file.path;
            res.sendFile(filePath);
    });
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the support, Using that I got the path of the image like this 'uploads/1621755676022-clipart2934035.png'. I try to load the image using "52.75.82.205:3000/myshop/uploads/…" But that show "cannot get" error , Can you help
Have you configured express app to serve static files in "uploads" directory ? Something like this app.use(express.static('uploads')). Then try http://52.75.82.205:3000/1621755676022-clipart2934035.png

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.