Skip to content

Instantly share code, notes, and snippets.

@wizardnet972
Created June 24, 2018 17:54
Show Gist options
  • Select an option

  • Save wizardnet972/9900c39570bf2067d8518acb7e6a9b37 to your computer and use it in GitHub Desktop.

Select an option

Save wizardnet972/9900c39570bf2067d8518acb7e6a9b37 to your computer and use it in GitHub Desktop.
fileupload nodejs
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