Express js upload file Multer js
Published: 2022-12-20 21:33:25

```
mkdir express_upload
cd express_upload
npm init -y

```

![Image node js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wvnuc2z8y0g4ws4m55bp.png)

kita butuh multer

![Image multer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t41ttl0orvghvlo6xm24.png)

```
npm install express dotenv prisma multer
npx prisma init
npm i -D @babel/core @babel/node @babel/preset-env
```
kita akan gunakan post man,

![Image postman](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t9xt3e8gt1k54dt8mk70.png)

kita buat file .babelrc

```
//.bablerc

{
    "presets": ["@babel/preset-env"]
}
```
selanjutnya kita akan buat folder src

![Image src](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m9kx0ph1sdg2yaz55evt.png)

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"
  }
}

```
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
```
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
```

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
```
tambahkan 8000

```
//.env

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

```
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...')
})
```
jalankan aplikasinya

`npm run dev`

![Image server run](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jzautnph80qcpi9qa8yn.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sa7g5nviehysnvsvvh51.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/esrstbhzdqsv8bjo45zt.png)

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

![Image success](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9z4barl20n9yd6rxf36o.gif)

sekarang file uploads terisi test.png.

![Image test.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/332z9au4s2g1xrwsj8qw.png)

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

![Image regis](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zum819z8lack1ruszquj.png)

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
```

![Image blog1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9khlxpm9zdeam7mnbazy.png)

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

[git repo](https://github.com/andiks2018/jvalleyExpress-uploadMulterJs.git)

Terima kasih.