Demo Upload Image Nodejs - Tips Nodejs

Nội dung bài viết

Video học lập trình mỗi ngày

Tạo mấy file đơn giản thôi. Bắt đầu.

index.html

<body>
 <input name="img" type="file">
 <button>submit</button>

 <script></script>
 <script></script>
</body>

test.js

$("button").on("click", function (e) {
 e.preventDefault()
 var obj = new FormData();
 obj.append("img",$("input").get(0).files[0]);
 $.ajax({
 url:"http://localhost:8081/test",
 type:"post",
 data:obj,
 Processing Data: false, // Not Processing Data
 ContentType: false, // No request header set
 cache:false,
 success:function(data){
 console.log(data)
 }
 })
})

node app.js

const express = require("express")
const fs = require("fs")
const formidable = require('formidable')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))

app.post("/test",function(req,res){
 // Cross-domain
 res.header("Access-Control-Allow-Origin", "*");
 res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
 res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
 
 let form = new formidable.IncomingForm();
 Form.encoding='utf-8'; //encoding
 Form. keep Extensions = true; // keep extensions
 Form.maxFieldsSize = 2 * 1024 * 1024; // file size
 Form.uploadDir ='C:/Users/Administrator/Downloads'//Storage Path
 Form. parse (req, function (err, fileds, files) {// parsing formData data
 if(err){ return console.log(err) }

 Let imgPath = files. img. path // Get the file path
 Let imgName = ". / test."+ files. img. type. split ("/") [1]/// modified name
 Let data = fs. readFileSync (imgPath) // Synchronized reading of files

 Fs. writeFile (imgName, data, function (err) {// Storage file

 if(err){ return console.log(err) }

 Fs.unlink (imgPath, function (){})// Delete files
 res.json({code:1})
 })
 })
})

app.listen(8081)

Có thể bạn đã bị missing