[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"blog-cats-ngidenet":3,"blog-detail-ngidenet-belajar-nodejs-upload-file":20},{"items":4},[5,9,13,17],{"name":6,"slug":7,"count":8},"Digital Marketing","digital-marketing",41,{"name":10,"slug":11,"count":12},"Programming","programming",56,{"name":14,"slug":15,"count":16},"Tips","tips",75,{"name":18,"slug":19,"count":8},"Web Development","web-development",{"id":21,"slug":22,"title":23,"short_text":24,"excerpt":24,"cover":25,"cover_image":25,"cover_alt_text":25,"category":10,"tags":26,"published_at":27,"created_at":28,"full_text":29,"meta_title":25,"meta_description":30,"faqs":31,"images":32,"views_count":33},452,"belajar-nodejs-upload-file","Belajar NodeJs - Cara Upload File dengan Nodejs","Masih dilanjutan series belajar nodejs. Kali ini kita akan mebahas bagaimana cara upload gambar \u002F file dengan menggunakan nodejs. Tutorial kali ini kita tidak akan menggunakan framework atau tambahan ",null,[],"2021-02-27T16:00:00Z","2026-07-14T04:39:40.796764Z","\u003Cp>Masih dilanjutan series belajar nodejs. Kali ini kita akan mebahas bagaimana cara upload gambar \u002F file dengan menggunakan nodejs.\u003C\u002Fp>\u003Cp>Tutorial kali ini kita tidak akan menggunakan framework atau tambahan module lainnya. Pure Node js.\u003C\u002Fp>\u003Cp>Hanya menggunakan module \u003Ccode>http\u003C\u002Fcode> dan \u003Ccode>fs\u003C\u002Fcode>.\u003C\u002Fp>\u003Cp>Penasaran seperti apa hasilnya nanti?\u003C\u002Fp>\u003Cp>Ikuti terus tutorial ini ya.\u003C\u002Fp>\u003Ch4>Daftar Isi:\u003C\u002Fh4>\u003Ch2>Persiapkan Webserver\u003C\u002Fh2>\u003Cp>Pertama buat sebuah folder dengan nama \u003Ccode>node-upload-file\u003C\u002Fcode>.\u003C\u002Fp>\u003Cp>Buat file \u003Ccode>index.js\u003C\u002Fcode> yang akan menjadi webserver kita dan isi dengan kode dibawah ini:\u003C\u002Fp>\u003Cpre>\u003Ccode>const http = require('http');\nconst fs = require('fs')\nlet port = 3000\nhttp.createServer((req, response) =&gt; {\n  \u002F**\n   * `\u002F` loads index.html\n   *\u002F\n  if (req.url == '\u002F' &amp;&amp; req.method.toLowerCase() == 'get') {\n    response.setHeader('Content-Type', 'text\u002Fhtml')\n    const stream = fs.createReadStream(`${__dirname}\u002Fzindex.html`)\n    \u002F\u002F No need to call res.end() because pipe calls it automatically\n    stream.pipe(response)\n  } \n  \u002F**\n   * `\u002FfileUpload` only works with POST\n   * Saves uploaded files to the root\n   *\u002F\n  else if (req.url == '\u002FfileUpload' &amp;&amp; req.method.toLowerCase() == 'post') {\n    response.setHeader('Content-Type', 'application\u002Fjson')\n    let contentLength = parseInt(req.headers['content-length'])\n    if (isNaN(contentLength) || contentLength &lt;= 0 ) {\n      response.statusCode = 411;\n      response.end(JSON.stringify({status: \"error\", description: \"No File\"}))\n      return\n    }\n    \u002F\u002F Try to use the original filename\n    let filename = req.headers['filename']\n    if (filename == null) {\n      filename = \"file.\" + req.headers['content-type'].split('\u002F')[1]\n    }\n    const filestream = fs.createWriteStream(`${__dirname}\u002F${filename}`)\n    filestream.on(\"error\", (error) =&gt; {\n      console.error(error)\n      response.statusCode = 400;\n      response.write(JSON.stringify({status: \"error\", description: error}))\n      response.end()\n    })\n    \u002F\u002F Write data as it comes\n    req.pipe(filestream)\n    req.on('end', () =&gt; {\n      filestream.close(() =&gt; {\n        response.end(JSON.stringify({status: \"success\"}))\n      })\n    })\n  } \n  \u002F**\n   * Error on any other path\n   *\u002F\n  else {\n    response.setHeader('Content-Type', 'text\u002Fhtml')\n    response.end(\"&lt;html&gt;&lt;body&gt;&lt;h1&gt;Page Doesn't exist&lt;h1&gt;&lt;\u002Fbody&gt;&lt;\u002Fhtml&gt;\")\n  }\n}).listen(port, () =&gt; {\n  console.log(`Server running at http:\u002F\u002Flocalhost:${port}\u002F`);\n})\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>\u003Cstrong>Penjelasan\u003C\u002Fstrong>\nKita hanya akan memiliki 2 request yaitu GET dan POST.\u003C\u002Fp>\u003Cp>\u003Cstrong>GET\u003C\u002Fstrong> akan berfungsi untuk menampilkan form html untuk upload file.\u003C\u002Fp>\u003Cp>\u003Cstrong>POST\u003C\u002Fstrong> akan berfungsi untuk mengupload file ke dalam server dan ditaruh di folder.\u003C\u002Fp>\u003Ch2>Buat view untuk upload file\u003C\u002Fh2>\u003Cp>Buat sebuah file dengan nama \u003Ccode>index.html\u003C\u002Fcode>. Dan isi dengan kode dibawah ini.\u003C\u002Fp>\u003Cpre>\u003Ccode>&lt;html&gt;\n  &lt;head&gt;\n  &lt;script&gt;\n  const handleImageUpload = event =&gt; {\n    const file = event.target.files[0]\n    if (file == null) return\n    fetch('\u002FfileUpload', {\n      headers: {\n        'filename': file.name\n      },\n      method: 'POST',\n      body: file\n    })\n    .then(response =&gt; response.json())\n    .then(data =&gt; {\n      console.log(data)\n    })\n    .catch(error =&gt; {\n      console.error(error)\n    })\n  }\n  function init() {\n    document.getElementById('fileUpload').addEventListener('change', event =&gt; {\n      handleImageUpload(event)\n    })\n  }\n  &lt;\u002Fscript&gt;\n  &lt;\u002Fhead&gt;\n  &lt;body onload=\"init()\"&gt;\n  &lt;input type=\"file\" id=\"fileUpload\" \u002F&gt;\n  &lt;\u002Fbody&gt;\n  &lt;\u002Fhtml&gt;\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>Jika sudah, maka jalankan perintah \u003Ccode>node index.js\u003C\u002Fcode>.\u003C\u002Fp>\u003Cp>Lalu buka \u003Ccode>localhost:3000\u003C\u002Fcode> dan kamu akan mendapatkan tampilan seperti ini.\u003C\u002Fp>\u003Cfigure>\u003Cfigcaption>\u003Ci>Demo upload file\u003C\u002Fi>\u003C\u002Ffigcaption>\u003C\u002Ffigure>\u003Cp>Coba select sebuah file, dan otomatis akan terupload di root folder directory project kamu.\u003C\u002Fp>\u003Cp>Mudah bukan?\u003C\u002Fp>\u003Cp>Ikuti terus tutorial belajar nodejs ini ya guys.\u003C\u002Fp>\u003Cp>\u003Cb>Series Belajar NodeJS Sebelumnya:\u003C\u002Fb>\u003C\u002Fp>\u003Col>\u003Cli>Belajar NodeJs - Dasar dan Persiapan Belajar NodeJs\u003C\u002Fli>\u003Cli>Belajar NodeJs - Mengenal Package Management NPM\u003C\u002Fli>\u003C\u002Fol>\u003Cp>\u003Cb>Series Belajar NodeJS Lainnya:\u003C\u002Fb>\u003C\u002Fp>\u003Col>\u003Cli>Belajar NodeJs - Cara Handle Form Input di Nodejs\u003C\u002Fli>\u003Cli>Belajar NodeJs - Membuat CRUD dengan NodeJs dan MySql\u003C\u002Fli>\u003C\u002Fol>","Masih dilanjutan series belajar nodejs. Kali ini kita akan mebahas bagaimana cara upload gambar \u002F file dengan menggunakan nodejs. Tutorial kali ini kita tidak a",[],[],0]