DEV Community

Cover image for Bag 2 - Upload with ExpressJS API
IRPAN KUSUMA W
IRPAN KUSUMA W

Posted on

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

Top comments (3)

Collapse
 
athenabarnarda profile image
AthenaBarnarda

How do I upload files using Express?
faithfulness spells

Collapse
 
irpankusuma profile image
IRPAN KUSUMA W

hello, sorry about my wording.

this article using express for saving files from frontend. Step to produce is

  1. install package npm i connect-multiparty
  2. on startter index.js on your application add file express.use('/v1/, require('upload.js'))
  3. finish

harusnya gitu doang sih bro

Collapse
 
athenabarnarda profile image
AthenaBarnarda

thank you sir