Created
March 13, 2021 06:32
-
-
Save Pompeu/b429c6564e6bc61ebc300c7a27291893 to your computer and use it in GitHub Desktop.
upload_file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//server | |
const express = require("express"); | |
const formidable = require("formidable"); | |
const app = express(); | |
app.post("/", (req, res, next) => { | |
const form = formidable({ | |
multiples: true, | |
keepExtensions: true, | |
uploadDir: "./img", | |
hash: "sha256", | |
}); | |
form.parse(req, (err, fields, files) => { | |
if (err) { | |
return res.json({ err: err.message }); | |
} | |
return res.json({ fields, files }); | |
}); | |
}); | |
app.listen(3000, () => { | |
console.log("Server listening on http://localhost:3000 ..."); | |
}) | |
//client | |
const http = require("http"); | |
const fs = require("fs"); | |
const formData = require("form-data")(); | |
const stream = fs.createReadStream("./exemple.txt"); | |
const req = http.request( | |
{ | |
host: "127.0.0.1", | |
port: 3000, | |
headers: formData.getHeaders(), | |
method: "POST", | |
}, | |
(res) => { | |
res.resume(); | |
res.on("data", (data) => { | |
console.log( | |
"Data received: ", | |
JSON.parse(JSON.stringify(data.toString())) | |
); | |
}); | |
res.on("end", () => { | |
if (!res.complete) { | |
console.error( | |
"The connection was terminated while the message was still being sent" | |
); | |
} | |
console.log("end"); | |
}); | |
} | |
); | |
req.on("error", (e) => { | |
console.error(e); | |
}); | |
formData.append("file", stream); | |
formData.pipe(req); | |
/* | |
{ | |
"name": "upload_files", | |
"version": "1.0.0", | |
"description": "", | |
"main": "server.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1", | |
"start": "node server.js" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"axios": "^0.21.1", | |
"body-parser": "^1.19.0", | |
"express": "^4.17.1", | |
"form-data": "^4.0.0", | |
"formidable": "^1.2.2", | |
"fs-extra": "^9.1.0", | |
"path": "^0.12.7" | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment