Bag 2 - Upload with ExpressJS API

irpankusuma

IRPAN KUSUMA W

Posted on March 11, 2022

Bag 2 - Upload with ExpressJS API

[Halo sobat]

Melanjutkan https://dev.to/irpankusuma/upload-file-dengan-xhr-2a3a. Sekarang saya akan menampilkan script API dengan ExpressJSnya. Pertama saya harap Anda sudah biasa menggunakan expressjs dan sudah pernah membuat sebuah API.

Kemudian sebelumnya install package multiparty berikut ini

npm i connect-multiparty
Enter fullscreen mode Exit fullscreen mode

Selanjutnya dalam file route yg akan digunakan codenya seperti berikut ini
upload.js


const router = require("express").Router();
const CPM = require("connect-multiparty");
const helper = require('helper.js');
const multiparty = CPM();
const target_path = `target_path`;

///// route file for access data from API
router.post("/", multiparty, async (req, res, next) => {
  try {
    const file = req.files.upload.path;
    let obj = {
      files: req.files,
      temp: req.files.upload.path,
      filename: req.files.upload.originalFilename,
      ext: req.files.upload.type,
      target_path: target_path,
    };

    ///// file berikut yg bertugas melakukan transfer file 
    ///// dari temp file ke local folder pada API project
    await helper.uploadFile(obj, file, target_path)
      .then(async (r) => {
        let data = {
          image_type: r.data.ext,
          real_path: r.data.target_path,
          real_filename: r.data.filename,
        };
        res.status(200).send(r);
      })
      .catch((e) => {
        throw e;
      });
  } catch (err) {
    res.status(401);
    console.log(`error ${err}`)
  }
});

module.exports = router;

Enter fullscreen mode Exit fullscreen mode

Kemudian selanjutnya adalah create helper.js
helper.js

const fs = require('fs')
const mv = require('mv')

module.exports = {
  uploadFile: (obj={},tmp_path,path) => {
    return new Promise((resolve,reject) => {
      try {
        const filename = path+obj.filename;
        if(!fs.existsSync(path)){
          fs.mkdirSync(path);
          mv(tmp_path,filename,function(err){
            if(err) reject(err)
            fs.unlink(tmp_path,function(){
              if(err) reject(err)
              resolve({status: true, message: 'Data uploaded success'})
            })
          })
        } else {
          mv(tmp_path,filename,function(err){
            if(err) reject(err)
            fs.unlink(tmp_path,function(){
              if(err) reject(err)
              resolve({status: false, message: 'Data uploaded failed!'})
            })
          })
        }
      } catch (error) {
        reject(error)
      }
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

Dalam expressJS mapping file upload.js pada routing seperti berikut ini

const router = require('express').Router()

router.use('/upload',require('./upload'))
Enter fullscreen mode Exit fullscreen mode

Selanjutnya Anda bisa mencoba menggunakan postman seperti berikut
Image description

💖 💪 🙅 🚩
irpankusuma
IRPAN KUSUMA W

Posted on March 11, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related