DEV Community

Cover image for Express js upload file Multer js
Andi Ismail
Andi Ismail

Posted on

Express js upload file Multer js

mkdir express_upload
cd express_upload
npm init -y

Enter fullscreen mode Exit fullscreen mode

Image node js

kita butuh multer

Image multer

npm install express dotenv prisma multer
npx prisma init
npm i -D @babel/core @babel/node @babel/preset-env
Enter fullscreen mode Exit fullscreen mode

kita akan gunakan post man,

Image postman

kita buat file .babelrc

//.bablerc

{
    "presets": ["@babel/preset-env"]
}
Enter fullscreen mode Exit fullscreen mode

selanjutnya kita akan buat folder src

Image src

selanjutnya kita akan hapus test diganti dengan dev

//package.json

{
  "name": "express_upload",
  "version": "1.0.0",
  "description": "",
  "main": "/src/index.js",
  "scripts": {
    "dev": "nodemon --exec babel-node ./src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "multer": "^1.4.5-lts.1",
    "prisma": "^4.7.1"
  },
  "devDependencies": {
    "@babel/core": "^7.20.5",
    "@babel/node": "^7.20.5",
    "@babel/preset-env": "^7.20.2"
  }
}

Enter fullscreen mode Exit fullscreen mode

masuk ke controller buat file upload_controller

//upload_controller.js

import {request, response} from "express"

const upload_create = async (req = request, res = response)=>{
    try{
        const data = await req.body
        return res.status(201).json({
            success : true,
            data : data
        })
    }catch(err){
        return res.status(500).json({
            success : false,
            error : err.message
        })
    }
}
export default upload_create
Enter fullscreen mode Exit fullscreen mode

selanjutnya kita akan buat upload_mdw.js

//upload_mdw.js

import multer from "multer";

const storage =multer.diskStorage({
    destination : (req, file, cb)=>{
        cb(null, './public/uploads')
    },
    filename : (req, file, cb)=>{
        cb (null, 'test.png')
    }
})

const upload_mdw = multer({storage : storage})

export default upload_mdw
Enter fullscreen mode Exit fullscreen mode

selanjutnya kita akan buat rootnya

//upload_route.js

import express from 'express'
import upload_create from '../controllers/upload_controller'
import upload_mdw from '../middleware/upload_mdw'

const upload_route = express.Router()

//create upload
upload_route.post("/api/upload/create", upload_mdw.single('file'), upload_create)

export default upload_route
Enter fullscreen mode Exit fullscreen mode

tambahkan 8000

//.env

DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"
PORT=8000

Enter fullscreen mode Exit fullscreen mode

selanjutnya kita ke index.js

//index.js

import express from 'express'
import env from 'dotenv'
import upload_route from './routes/upload_route'
env.config()

const app = express()
const {PORT} =process.env

app.use(express.static("../public"))
app.use(express.json())

app.use(upload_route)

app.listen(PORT, ()=>{
    console.info('server running...')
})
Enter fullscreen mode Exit fullscreen mode

jalankan aplikasinya

npm run dev

Image server run

selanjutnya kita akan ke postman, buat create new collection , upload folder, add request, post, lanjut ke body, klik rubah jadi form-data, uncentang description, key isi dengan file, kemudian valuenya, select files

Image postman

berhasil menampilkan file upload, selanjutnya kita akan buat 2 folder public/uploads kosongan nanti akan terisi ketika kitta klik upload dari post man

Image uploads

kenapa nama file nya puploads karena folder yang kita buat nama filesnya adalah ./public/uploads ok, sekarang kita ke post man

Image success

sekarang file uploads terisi test.png.

Image test.png

dan kalau kita upload lagi maka akan menghasilkan test.png lagi dan niban data yang lama.

Image regis

kita ganti 'test.png' menjadi original name

//upload_mdw.js

import multer from "multer";
//buat storagenya
const storage =multer.diskStorage({
    destination : (req, file, cb)=>{
        cb(null, './public/uploads')
    },
    filename : (req, file, cb)=>{
        cb (null, file.originalname) //ganti file ini
    }
})
const upload_mdw = multer({storage : storage})
export default upload_mdw
Enter fullscreen mode Exit fullscreen mode

Image blog1

sekarang kita sudah bisa upload file sesuai dengan nama file aslinya.

git repo

Terima kasih.

Top comments (0)