Answer the question
In order to leave comments, you need to log in
How to upload file to node.js server without 3rd party libraries?
How to upload file to node.js server without third party libraries? What happens to a file when it is uploaded via a form? What format does it take? And how to view the real contents of this file?
Here is the html code of the page where there is only input for uploading a file and a button for submitting the form
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form id="file_load">
<input type="file" name="myfile">
<input type="submit" value="Загрузить">
</form>
<script src="script.js"></script>
</body>
</html>
file_load.onsubmit = function(){
var file = this.elements.myfile.files[0];
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload", true);
xhr.send(file);
return false;
}
const server = require('http').createServer();
var fs = require('fs');
var static = require('node-static');
var file = new static.Server('.', {
cache: 0
});
server.listen(3000,()=> console.log("сервер запущен"));
server.on('request',(req,res)=>{
if (req.url == '/upload') {
var body = "";
req.on('data', function(chunk) {
body+=chunk;
}).on('end',function(){
fs.writeFileSync("file2.jpg",body);
res.end('ok');
})
}else{
file.serve(req, res);
}
});
var reader = new FileReader();
file_load.onsubmit = function(){
var file = this.elements.myfile.files[0];
reader.readAsText(file);
return false;
}
reader.onload = function(e) {
file = e.target.result;
upload(file);
}
function upload(file){
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload", true);
xhr.send(file);
}
Answer the question
In order to leave comments, you need to log in
In this case, the file is sent in the request body as is, without any wrappers:
file_load.onsubmit = function(){
var file = this.elements.myfile.files[0];
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload", true);
xhr.send(file);
return false;
}
const server = require('http').createServer();
const fs = require('fs');
const nodeStatic = require('node-static');
const file = new nodeStatic.Server('.', {
cache: 0
});
server.listen(3000, () => console.log("сервер запущен"));
server.on('request', (req, res) => {
if (req.url == '/upload') {
req.pipe(
fs.createWriteStream('file2.jpg')
).on('finish', () => res.end('ok'));
return;
}
file.serve(req, res);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question