I have a webpage with a form, the form has a file input, and when I submit the form I would like the server to write it to a file server side.
I have tried uploading several test images using this form, and so far every one turns out as a plain text file containing the original file's filename. I have found no good information or examples of how to do this online except for "use Express!", "use This!", "use That!", "use The Other Thing!" and it's quite aggravating.
I agree with what Tomalak said in the comments; the problem you're trying to solve with Node alone and no libraries is not trivial, and requires a pretty thorough understanding of multiple different technologies.
That said, I'll help get you started, and hopefully this will be a good jumping-off point for reading source code of the modules that do do this.
Using nothing but Node, here's a minimal server that will log to the console the body of any request (I do not recommend sending a big file to this, or a binary file...start with text files):
var http = require('http');
var server = http.createServer(function(req, res) {
if(req.url === '/favicon.ico') return res.statusCode = 404, res.end();
console.log(req.method + ' ' + req.url);
var data = '';
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
console.log(data);
});
res.end('done');
});
server.listen(3000, function() {
console.log('listening on 3000');
});
Then you can create an HTML form to connect to it:
<!doctype html>
<html>
<head>
</head>
<body>
<form action="http://localhost:3000" method="POST" enctype="multipart/form-data">
<input type="file" name="f">
<input type="submit">
</form>
</body>
</html>
Parsing multipart/form-data
is not a trivial task, but you can start by reading the documentation here:
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4
If you want to look at someone's implementation of a multipart/form-data
parser, this one is pretty solid:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.