Vacation.findById(req.params.id, function(vacation){ var form = new mp.Form(); //Parses the request object form.parse(req, function(err, fields, files){ //put files in vacation.uploadPhotos vacation.uploadPhotos(files, function(){ //Once called back, redirects to /vacations/:id res.redirect('/vacations/' + req.params.id); }); }); });
exports.create = (req, res)=>{ var form = new multiparty.Form(); form.parse(req, (err, field, file)=>{ var album = {}; album.name = field.name[0]; album.photo = file.photo[0].originalFilename; mkdirp(`${__dirname}/../static/img/${album.name}`, function(err) { fs.renameSync(file.photo[0].path,`${__dirname}/../static/img/${album.name}/${album.photo}`); }); albums.save(album, ()=>res.redirect('/albums')); }); };
exports.create = (req, res) => { var form = new multiparty.Form(); form.parse(req, (err, field, file)=>{ var artist = {}; artist.name = field.name[0]; artist.art = file.art[0].originalFilename; mkdirp(`${__dirname}/../static/img/${artist.name}`, function(err){ fs.renameSync(file.art[0].path, `${__dirname}/../static/img/${artist.name}/${artist.art}`); }); artists.save(artist, ()=>res.redirect('/artists')); }); };
exports.create = function(req, res){ var form = new mp.Form(); //console.log(req.body); form.parse(req, function(err, fields, files){ console.log('FIELDS', fields); Trip.create(fields, files, function(){ //Trip.create(req.body, function(){ // console.log('FORM', fields, files); res.redirect('/trips'); }); }); };
app.post('/upload', function(req,res){ var multiparty = require('multiparty'); var form = new multiparty.Form(); form.parse(req, function(err, fields, files) { console.log('path' + files.file[0].path); var file = files.file[0]; var path = file.path ; /* var mongo = require('mongodb'); var Grid = require('gridfs-stream'); // create or use an existing mongodb-native db instance var db = new mongo.Db('mydb', new mongo.Server("127.0.0.1", 27017)); */ var mongo = require('mongodb'); var Grid = require('gridfs-stream'); var fs = require('fs'); var MongoClient=mongo.MongoClient, server=mongo.Server; var mongoclient=new MongoClient(new server('localhost',27017)); mongoclient.connect('mongodb://localhost:27017/mydb',function(err,db) { var gfs = Grid(db, mongo); // streaming to gridfs console.log(file.originalFilename); var writestream = gfs.createWriteStream({ filename: file.originalFilename }); fs.createReadStream(path).pipe(writestream); console.log('success' + path); // streaming from gridfs var readstream = gfs.createReadStream({ filename: file.originalFilename }); //error handling, e.g. file does not exist readstream.on('error', function (err) { console.log('An error occurred!', err); throw err; }); readstream.pipe(res); }); }); });
this.saveImage = function (req, res, next) { form = new multiparty.Form(); id = req.params.id; uploadFile = { path: '', size: '', type: '' }; maxSize = 2 * 1024 * 1024; supportMimeTypes = ['image/jpg', 'image/jpeg', 'image/png']; errors = []; form.on('error', function (err) { if (err) { next() } // ToDO: удалять файлы, название которых - _id, игнорировать разрешение !!! if (fs.existsSync(uploadFile.path)) { fs.unlinkSync(uploadFile.path); } }); form.on('part', function (part) { uploadFile.size = part.byteCount; uploadFile.type = part.headers['content-type']; extention = (uploadFile.type).substring((uploadFile.type).indexOf('/') + 1).toString(); uploadFile.path = './public/images/avatars/' + id + '.' + extention; if (uploadFile.size > maxSize) { errors.push('File size is ' + uploadFile.size + '. Limit is' + (maxSize / 1024 / 1024) + 'MB.'); } if (supportMimeTypes.indexOf(uploadFile.type) == -1) { errors.push('Unsupported mimetype ' + uploadFile.type); } if (errors.length != 0) { return next(new HttpError(400, errors)); } out = fs.createWriteStream(uploadFile.path); part.pipe(out); }); form.on('close', function () { console.log('Upload completed!'); console.log((uploadFile.path).substr([9])); req.body.avatar = (uploadFile.path).substr(9); next(); }); form.parse(req); };
app.post(conf.tarReceiverUrl, function (req, res, next) { if (conf.disableReceiver) { return next(new Error('yog2 upload service was disabled')); } var to = null; var filePart = null; // 最大200mb var form = new multiparty.Form({ maxFieldsSize: conf.maxTarSize }); function tryExtract() { if (filePart && to) { extract(filePart, to, function () { reloadApp(); reloadView(); reloadIsomorphic(); ev.emit('cacheClean'); conf.onCacheClean && conf.onCacheClean(); }); } } form.on('error', function (err) { return next(err); }); form.on('part', function (part) { if (!part.filename) { streamToString(part, function (val) { debuglog('got to: [%s]', val); to = val; tryExtract(); }); } if (part.filename) { filePart = part; tryExtract(); } part.on('error', function (err) { return next(err); }); }); form.on('close', function () { res.end('0'); }); form.parse(req); });
router.post("/uploadFile", function(req, res) { var form = new multiparty.Form(); form.parse(req, function(err, fields, files) { console.log(files); for (var i = 0; i < files.files.length; i++) { var uploadedFile = files.files[i]; FileManager.saveUploadedFile(uploadedFile, fields.currentFolder[0]); } res.send("ok"); }); });
module.exports = function(req, res, next) { var form = new multiparty.Form(); form.on('part', function(part) { if (!part.filename) return; uploadToS3(part, function(err, data) { if (err) return next(err); res.json(data); }); }); form.on('error', next); form.parse(req); };
server.use(function(req, res, next) { if (req.method === 'POST' && req.headers['content-type'].split(';')[0] === 'multipart/form-data') { const form = new Multiparty.Form(); form.parse(req, function(error, fields, files) { req.files = files; next(error); }); } else next(); });
router.post('/photo', function(req, res) { console.log('photo'); var form = new multiparty.Form(); var picture = new Picture(); var type = req.query.parenttype; form.parse(req, function(err, fields, files) { for (var i = 0, len = files.files.length; i < len; i++) { var path = files.files[i].path; var n = path.lastIndexOf("/") + 1; var tempName = path.substring(n); var originalName = files.files[i].originalFilename; var filePath = '/var/www/html/nodeJS/weC/uploads/' + tempName; picture.filename = originalName; picture.filelocation = filePath; picture.parentid = req.query.parentid; picture.parenttype = req.query.parenttype; picture.save(function () { req.pictureid = picture._id; console.log(picture._id); if(type == 'event'){ Event.setPic( req , function(err, event) { res.send(event); }); }else if(type == 'biz'){ Biz.setPic( req , function(err, biz) { res.send(biz); }); }else if(type == 'tribe'){ Tribe.setPic( req , function(err, tribe) { res.send(tribe); }); }else if(type == 'profile'){ User.setPic( req , function(err, user) { res.send(user); }); } }); console.log(path); var tfile = fs.readFileSync(path); fs.writeFile(filePath,tfile); } }); });
self.put = function(req, res, callback) { var table = rootPath + "/db/" + sanitizeUrl("table", req); var id = sanitizeUrl("id", req); var data = sanitizeUrl("data", req); var form = new multiparty.Form(); if (table.match(/^(.*?(\_User\b)[^$]*)$/)) { protectedCallback(res, callback, { error: "Calls to _User are not allowed" }); } else { var thisDb = getDB(table); // handle the FormData form.parse(req, function(err, allFields, files) { var fields = sanityzeAndRemoveEmpty(allFields); fields.updatedAt = new Moment().format('x').toString(); thisDb.loadDatabase(function (err) { if (err) { protectedCallback(res, callback, { error: err }); } else { // Set an existing field's value thisDb.update({ _id: id }, { $set: fields }, function (err, numReplaced) { if (err) { protectedCallback(res, callback, { error: err }); } else { var first = null; var firstKey = null; for (var firstKey in files) { first = files[firstKey]; if(typeof(first) !== 'function') { break; } } if(files && files[firstKey]) { // If there's a file, upload it saveFiles(table, id, files, callback) // TODO how to keep the files? } else { // no uploading neccessary protectedCallback(res, callback, { _id: id }) } } }); } }); }); } }
router.post('/upload', function(req, res, next) { var form = new multiparty.Form( { maxFilesSize: config.maxSongFileSize } ); form.parse(req, function(err, fields, files){ if(err){ return next(err); } //input validation if(fields && fields.songId[0] !== 'undefined' && files.file[0] && files.file[0].headers["content-type"] === 'image/jpeg' && req.user){ var args = { songId: fields.songId[0], userId: req.user._id, filePath: files.file[0].path }; //add image controller.add(args, function(err){ //first, delete file here since it was created here by form.parse fs.unlink(files.file[0].path, function(err){ if(err){ erroController.reportError(err); } }); //then return err if any if (err) { return next(err); } //return output if all is good var output = { data: {} }; render(res, output); }); } else{ //also delete file if input was invalid fs.unlink(files.file[0].path, function(err){ if(err){ erroController.reportError(err); } }); //report file type error if (files.file[0] && files.file[0].headers && files.file[0].headers["content-type"]) { erroController.reportError({ 'status': 'Upload Image - Invalid Input', 'message': 'File submitted was of content-type: ' + files.file[0].headers["content-type"] }); } //return err return next(new Error('Invalid Input!')); } }); });
router.post('/import', isAuthenticated, (req, res) => { const form = new multiparty.Form(); form.parse(req); form.on('file', function (name, file) { race.import(file.path); }); form.on('close', function () { res.redirect('/admin/after'); }); form.on('error', function (err) { console.log(err); }); });
app.use(function (req, res, next) { req.uploadDir = app.get('uploadDir'); req.uploadRelative = app.get('uploadRelative'); if(req.method === 'POST' && req.headers['content-type'].indexOf("multipart/form-data") !== -1){ var form = new multiparty.Form(); form.parse(req, function(err, fields, files){ req.files = files; next(); }); } else { next(); } });
app.post('/apis/upload',function(req,res,next){ var form = new multiparty.Form({uploadDir:'./public/ups/'}); form.parse(req,function(err,fields,files){ var filesTmp = JSON.stringify(files,null,2); if(err){ console.log('Form Parse error:'+err); }else{ // console.log(filesTmp); var inpageUrl = files.file[0].path.split('public')[1]; res.send({url:inpageUrl}); } }); });
module.exports.processForm = function( req, res, next ) { var form = new multiparty.Form(); form.parse( req, function( err, fields, files ) { if ( err ) { return next( utils.error( 500, err ) ); } req.body = fields; req.files = files; next(); }); };
router.post("/graphs/", function(req, res, next) { // fs.writeFile(path.join(config.active_dir, req.body.filename), req.body.contents, function(err) { // if(err) { // res.status(500).send({error: err}); // } // res.send({success: true}); // }); // Configure multi-part form uploads. var options = { autoFiles: true, uploadDir: config.active_dir }; var form = new multiparty.Form(options); // Handle multi-part form data. form.parse(req, function(err, fields, files) { // If there was some kind of error parsing the multi-part form, // forward it to our error handler and bail out. if (err) { next(err); return; } // Make sure we actually have a filename field in whatever form is // submitting the request. if (!fields.hasOwnProperty("filename")) { throw "No filename property."; } // We must have at least something file-like for the gcl_content field. if (!files.hasOwnProperty("contents")) { throw "No contents"; } // At this point, Multiparty will have uploaded the file to the graphs // directory, but it won't be the name that we want. We'll go ahead and // move the file to the proper location. var temp = files.contents[0].path; var dest = path.join(config.active_dir, fields.filename[0]); fs.rename(temp, dest, function(err) { if (err) { next(err); res.status(500).end(); return; } res.status(200).end(); }); }); });
Pluploader.prototype.handleRequest = function plupload(req, res) { var form = new multiparty.Form(this.options), self = this; form.parse(req, function(err, fields, files) { if (!fields.chunk) { fields.chunk = [0]; fields.chunks = [1]; } var name = fields.name[0], chunks = fields.chunks[0]; var fileIdentifier = name + chunks[0]; if (!self.pendingUploads[fileIdentifier]) { self.pendingUploads[fileIdentifier] = { name: name, files: [], updated: +new Date(), chunks: chunks }; } // TODO find a way to prevent upload from going to FS fs.readFileAsync(files.file[0].path) .then(function(fileData) { self.pendingUploads[fileIdentifier].tempPath = files.file[0].path; self.pendingUploads[fileIdentifier].files.push(fileData); self.uploadLimitReached(fileIdentifier).then(function(limitReached) { if (limitReached) { self.emit('error', { 'message': 'File size exceeds upload limit of ' + self.options.uploadLimit + 'M' }); } else { self.finalizePendingUploads(req); } }); }) .error(function(error) { self.emit('error', error); }); }); };
app.post( "/tweet", function(req, res ){ var form = new multiparty.Form(); form.parse(req, function(err, fields, files) { res.writeHead(200, {'content-type': 'text/plain'}); res.write('received upload:\n\n'); res.end(util.inspect({fields: fields, files: files})); if( fields.image ){ if( req.session.oauthAccessToken ){ var collection = followersDatabase.collection( 'tokens' ); collection.findOne( { 'oauth_access_token': req.session.oauthAccessToken }, function( err, item ) { console.log( 'found' ); var config = { consumer_key: process.env.TWITTER_CONSUMER_KEY, consumer_secret: process.env.TWITTER_CONSUMER_SECRET, token_secret: item.oauth_access_token_secret, token: item.oauth_access_token } var image = decodeURIComponent( fields.image[0] ); var matches = image.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/) var imageData = new Buffer(matches[2], 'base64'); var m = new media(config); m.post( fields.message[0], imageData, function(err, response) { if (err) { console.log( 'ERROR' ); console.log(err); }else{ console.log( 'SUCCESS' ); } console.log(response); }); }); } } }); } );
this.uploadSchedule = function(req,res){ var form = new multiparty.Form({uploadDir: '../upload/'}); //上传完成后处理 form.parse(req, function(err, fields, files) { var file = JSON.parse(JSON.stringify(files,null,2)); var data = JSON.parse(JSON.stringify(fields,null,2)); if(err){ console.log('parse error: ' + err); } else { if(file.file){ var uploadedPath = file.file[0].path+''; var dstPath = '../upload/' + file.file[0].originalFilename; //重命名为真实文件名 fs.rename(uploadedPath, dstPath, function(err) { if(err){ console.log('rename error: ' + err); }else{ var orderData = read.readFile('./orderSchedule.js'); var time = new Date().getTime(); var newData = JSON.stringify({'uuid':data.orderid[0],'schedule':data.schedule[0],'scheduleImage':dstPath,'uploadTime':time}); if(orderData!='') orderData = orderData+','+newData; else orderData = newData; if(this.writeFile('./orderSchedule.js',orderData)) { res.writeHead(200, {'Content-Type': 'application/json'}); res.write(JSON.stringify({S0023:"ORDER_SUCCESS"})); res.end(); } } }); } else{ var orderData = read.readFile('./orderSchedule.js'); var time = new Date().getTime(); var newData = JSON.stringify({'uuid':data.orderid[0],'schedule':data.schedule[0],'uploadTime':time}); if(orderData!='') orderData = orderData+','+newData; else orderData = newData; if(this.writeFile('./orderSchedule.js',orderData)) { res.writeHead(200, {'Content-Type': 'application/json'}); res.write(JSON.stringify({S0023:"ORDER_SUCCESS"})); res.end(); } } } }); }
router.post('/love-record/upload', function (req, res, next) { //生成multiparty对象,并配置上传目标路径 var form = new multiparty.Form({ uploadDir: './public/images/love-record/' }); //上传完成后处理 form.parse(req, function (err, fields, files) { var filesTmp = JSON.stringify(files, null, 2); if (err) { console.log('parse error: ' + err); } else { var inputFile = files.inputFile[0]; var uploadedPath = inputFile.path; //重名为当前最大的一个数字 var files = rd.readSync('./public/images/love-record'); var max = 0; files.map(function (str) { var file = path.basename(str); //大于10位位随机文件 if (file.length < 10) { var s = file.split("."); var rank = parseInt(s[0]); if (!isNaN(rank)) { max = Math.max(rank, max); } } }); var dstPath = './public/images/love-record/' + (max + 1) + '.' + inputFile.originalFilename.split('.')[1]; fs.rename(uploadedPath, dstPath, function (err) { if (err) { console.log('rename error: ' + err); } else { console.log('rename ok'); } }); } res.writeHead(200, { 'content-type': 'text/plain;charset=utf-8' }); res.write('received upload:\n\n'); //写入says信息 file.append(path.resolve(__dirname, '../public/config/says.txt'), fields.say[0] + '\n'); res.end(util.inspect({ fields: fields, files: filesTmp })); }); });
app.post('/api/1/credential/file', function (req, res, next) { // console.log(req.body.split('\n')); // // if (req.body.credential) { // } var form = new multiparty.Form(); form.parse(req, function (err, fields, files) { var credential = files.credential[0]; if (credential.size == 0) { res.send('no file'); return; } fs.readFile(credential.path, function (err, data) { if (err) { return res.send('read failed'); } new AV.File(credential.originalFilename, data).save() .then(function (theFile) { var lines = new Buffer(data).toString('utf8').split('\n'); lines.forEach(function (l) { var parts = l.split(' '); var credential = new Credential(); credential.set('protocol', parts[0]); credential.set('host', parts[2]); credential.set('username', parts[5]); credential.set('password', parts[8]); var query = new AV.Query(Credential); query.equalTo('protocol', parts[0]); query.equalTo('host', parts[2]); query.equalTo('username', parts[5]); query.equalTo('password', parts[8]); query.first().then(function (c) { if (!c) { return credential.save(); } }, function (err) { return credential.save(); }).then(function (c) { console.log(c.id); }, function (err) { console.log(err); }) }) res.send(lines); }).catch(next); }); }); });
exports.create = (req, res)=>{ var form = new multiparty.Form(); var userId = req.session.userId; form.parse(req, (err, fields, files)=>{ var project = {}; project.title = fields.title[0].trim(); project.description = fields.description[0].trim(); project.tags = fields.tags[0].split(',').map(t=>t.toLowerCase()).map(x=>x.trim()); project.gitURL = fields.gitURL[0].trim(); project.appURL = fields.appURL[0].trim(); project.date = new Date(fields.date[0]); project.userId = userId; console.log(fields); project.photos = []; console.log(files); var photoOrigPaths = []; files.photos.forEach(p=>{ project.photos.push(`/img/${userId}/${project.title}/${p.originalFilename}`); photoOrigPaths.push(p.path); console.log(fields); console.log(files); console.log(p); }); if(project.photos.length > 0){ if(!fs.existsSync(`${__dirname}/../static/img/${userId}`)){ fs.mkdirSync(`${__dirname}/../static/img/${userId}`); } if(!fs.existsSync(`${__dirname}/../static/img/${userId}/${project.title}`)){ fs.mkdirSync(`${__dirname}/../static/img/${userId}/${project.title}`); } project.photos.forEach((path, i)=>{ fs.renameSync(photoOrigPaths[i], `${__dirname}/../static/${path}`); }); } var projectObject = new Project(project); console.log('----------OBJECT-----------------'); console.log(projectObject); projects.save(project, ()=>res.redirect(`/project/show/${project._id}`)); }); };
exports.create = (req, res)=>{ var form = new multiparty.Form(); form.parse(req, (err, field, file)=>{ var album = {}; album.name = field.name[0]; album.photo = []; file.photo.forEach(p=>{ fs.renameSync(p.path, `${__dirname}/../static/img/${p.originalFilename}` ); album.photo.push(p.originalFilename); }); albums.save(album, ()=>res.redirect('/albums')); }); };
exports.create = function(req, res){ // console.log('server-controller-create >>>>>>>> req.user._id: ', req.user._id); // console.log('server-controller-create >>>>>>>> req.body: ', req.body); var form = new mp.Form(); form.parse(req, function(err, fields, files){ console.log('server-controller-create >>>>>>>> fields: ', fields); console.log('server-controller-create >>>>>>>> files: ', files); var projectInfo = JSON.parse(fields.project[0]); console.log('server-controller-create >>>>>>>> projectInfo: ', projectInfo); Project.create(req.user._id, projectInfo, files, function(err, success, project){ res.send({project:project}); }); }); };
var finalize = function (data) { form.removeListener('error', onError); form.removeListener('part', onPart); form.removeListener('field', onField); form.removeListener('close', onClose); if (arrayFields) { data = Qs.parse(data); } request.payload = data; return next(); };
router.post('/submissions', jwtCheck, function (req, res) { console.log(req.get('content-type')); var form = new multiparty.Form(); form.parse(req); hzrUtils.saveHZR(req.user, form, function (err, hzr) { if (err) { logger.log('info','Error saving hot zone report: %s', JSON.stringify(err)); res.send(500, {error: 'There was an error while saving your submission.'}) } else { res.json(201, hzr); } }); });
router.post('/submissions', jwtCheck, function (req, res) { console.log(req.get('content-type')); var form = new multiparty.Form(); form.parse(req); minUtils.saveSubmission(req.user, form, function (err, obs) { if (err) { console.log('Error saving MIN submission : %s', JSON.stringify(err)); res.send(500, {error: 'There was an error while saving your submission.'}) } else { res.json(201, obs); } }); });
self.post = function (req, resp, callback) { var table = rootPath + "/db/" + sanitizeUrl("table", req); if (table.match(/^(.*?(\_User\b)[^$]*)$/)) { protectedCallback(resp, callback, { error: "Calls to _User are not allowed" }); } else { var form = new multiparty.Form(); var thisDb = getDB(table); // handle the FormData form.parse(req, function (err, allFields, files) { var fields = sanityzeAndRemoveEmpty(allFields); fields.createdAt = new Moment().format('x').toString(); thisDb.loadDatabase(function (err) { if (err) { protectedCallback(resp, callback, { error: err }); } else { thisDb.insert(fields, function (err, newDoc) { if (err) { protectedCallback(resp, callback, { error: err }); } else { var first = null; var firstKey = null; for (var firstKey in files) { first = files[firstKey]; if(typeof(first) !== 'function') { break; } } if (files && files[firstKey]) { // If there's a file, upload it saveFiles(table, newDoc._id, files, callback); } else { // no uploading neccessary protectedCallback(resp, callback, { _id: newDoc._id }); } } }); } }); }); } }