Search code examples
node.jsmulter

node js get image url


i want to 1-choose an image from my filesystem and upload it to server/local 2- get its url back using node js service . i managed to do step 1 and now i want to get the image url instead of getting the success message in res.end here is my code

app.post("/api/Upload", function(req, res) {
upload(req, res, function(err) {
    if (err) {
        return res.end("Something went wrong!");
    }
    return res.end("File uploaded sucessfully!.");
});
});

i'm using multer to upload the image.


Solution

  • You can do something like this, using AWS S3 and it returns the url of the image uploaded

    const AWS = require('aws-sdk')
    
    AWS.config.update({
      accessKeyId: <AWS_ACCESS_KEY>,
      secretAccessKey: <AWS_SECRET>
    })
    
    const uploadImage = file => {
      const replaceFile = file.data_uri.replace(/^data:image\/\w+;base64,/, '')
      const buf = new Buffer(replaceFile, 'base64')
    
      const s3 = new AWS.S3()
      s3.upload({
        Bucket: <YOUR_BUCKET>,
        Key: <NAME_TO_SAVE>,
        Body: buf,
        ACL: 'public-read'
      }, (err, data) => {
        if (err) throw err;
    
        return data.Location; // this is the URL
      })
    }
    

    also you can check this express generator, which has the route to upload images to AWS S3 https://www.npmjs.com/package/speedbe