Created
June 24, 2018 17:54
-
-
Save wizardnet972/9900c39570bf2067d8518acb7e6a9b37 to your computer and use it in GitHub Desktop.
fileupload nodejs
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
| http://localhost:3000/upload | |
| node: | |
| var express = require('express'); | |
| var app = express(); | |
| var path = require('path'); | |
| var formidable = require('formidable'); | |
| var fs = require('fs'); | |
| var cors = require('cors'); | |
| var os = require('os'); | |
| var util = require('util'); | |
| app.use(cors()); | |
| app.use(express.static(path.join(__dirname, 'public'))); | |
| app.get('/', function(req, res) { | |
| res.sendFile(path.join(__dirname, 'views/index.html')); | |
| }); | |
| app.post('/upload', function(req, res) { | |
| var form = new formidable.IncomingForm(), | |
| files = [], | |
| fields = []; | |
| form.uploadDir = os.tmpdir(); | |
| form | |
| .on('field', function(field, value) { | |
| console.log(field, value); | |
| fields.push([field, value]); | |
| }) | |
| .on('file', function(field, file) { | |
| console.log(field, file); | |
| files.push([field, file]); | |
| }) | |
| .on('end', function() { | |
| console.log('-> upload done'); | |
| console.log('files', files); | |
| files.forEach(f => { | |
| const [filename, file] = f; | |
| fs.renameSync(file.path, path.resolve('uploads', filename)); | |
| }); | |
| res.writeHead(200, { 'content-type': 'text/plain' }); | |
| res.write('received fields:\n\n ' + util.inspect(fields)); | |
| res.write('\n\n'); | |
| res.end('received files:\n\n ' + util.inspect(files)); | |
| }); | |
| form.parse(req); | |
| }); | |
| var server = app.listen(3000, function() { | |
| console.log('Server listening on port 3000'); | |
| }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment