本文整理汇总了TypeScript中formidable.IncomingForm类的典型用法代码示例。如果您正苦于以下问题:TypeScript IncomingForm类的具体用法?TypeScript IncomingForm怎么用?TypeScript IncomingForm使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IncomingForm类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: function
upload.post('/uploading', function(req, res, next) {
if (req.method.toLowerCase() == 'post') {
//5.
var fmr = new frd.IncomingForm();
fmr.parse(req, function (err, fields, files) {
res.writeHead(200, { 'content-type': 'text/plain' });
});
fmr.on('end', function (fields, files) {
//6.
var tempPath = this.openedFiles[0].path;
//7.
var fileName = this.openedFiles[0].name;
//8.
var newFileName = "//D-113077851/GopikrishnaShare/PSPMarketPlace/"+ fileName; //../FileUpload_" + fileName;
//9.
filestore.copy(tempPath, newFileName, function (err) {
if (err) {
console.error(err);
} else {
res.end();
}
});
});
return false;
}
});
示例2: switch
const server = http.createServer((req, res) => {
switch (req.method) {
case "GET":
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(form);
break;
case "POST":
let incoming = new formidable.IncomingForm();
incoming.uploadDir = 'uploads';
// create the dir if unexisted
if (!fs.existsSync(incoming.uploadDir)) fs.mkdirSync(incoming.uploadDir);
// event listener
incoming.on('file', (field, file) => {
if (!file.size) { return; }
res.write(`${file.name} received\n`);
}).on('field', (field, value) => {
// unreacted: the module is long time to mantain
res.write(`${field} : ${value} \n`);
}).on('end', () => {
res.end('All files received');
});
// parse request
incoming.parse(req);
break;
}
}).listen(8080);
示例3: avatar
export function avatar(req: Request, res: Response): void {
const [creator, creatorRef] = UTIL.getLoginedUser(req),
UserModel: Model<IUser> = UTIL.getModelFromName(creatorRef),
root: string = UTIL.getRootFolderFromModelName(creatorRef),
now: string = UTIL.getTimestamp().toString()
let form: IncomingForm = new IncomingForm(),
filePath = path.join(root, creator.toString(), now),
log = {
creator,
creatorRef,
action: CONST.USER_ACTIONS.COMMON.UPDATE,
ua: req.body.ua || req.ua
}
form.multiples = false
form
.on('file', (fields: Fields, file: any) => {
let formData = {
type: CONST.IMAGE_TYPES.AVATAR,
path: filePath,
file: {
value: fs.createReadStream(file.path),
options: {
filename: UTIL.renameFile(file.name)
}
}
}
request.post({
url: SERVERS.UPLOAD_SERVER,
formData
}, (err: Error, response, body) => {
if (err) console.log(err)
let fileName = JSON.parse(body).files[0],
filePath = path.join(now, fileName)
UserModel
.findByIdAndUpdate(creator, {avatar: filePath}, {new: true})
.then((user: IUser) => {
if (user) {
res.status(200).json(UTIL.getSignedUser(user))
new Logger(log)
}
})
.catch((err: Error) => {
new Err(res, err, log)
})
})
})
.on('error', (err: Error) => {
res.status(500).json({err})
})
form.parse(req)
}
示例4: Promise
return new Promise((resolve, reject) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(ctx.req, (err, fields: formidable.Fields, files: formidable.Files) => {
if (err) return reject(err);
resolve({ fields, files });
});
});
示例5: switch
const server = http.createServer((req, res) => {
// create the dir if unexisted
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir);
// Process request
switch (req.method) {
case "GET":
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(form);
break;
case "POST":
let incoming = new formidable.IncomingForm();
incoming.uploadDir = uploadDir;
// event listener
incoming.on('file', (field, file) => {
if (!file.size) { return; }
res.write(`${file.name} received\n`);
}).on('field', (field, value) => {
// unreacted: the module is long time to mantain
res.write(`${field} : ${value} \n`);
}).on('end', () => {
res.end('All files received');
});
// parse request
incoming.parse(req);
break;
case "PUT":
let contentLength = Number(req.headers['content-length']);
let fileData = Buffer.alloc(contentLength);
let bufferOffset = 0;
req.on('data', (chunk) => {
chunk.copy(fileData, bufferOffset);
bufferOffset += chunk.length;
}).on('end', () => {
let rand = (Math.random() * Math.random())
.toString(16).replace('.', '');
let to = `${uploadDir}/${rand}-${req.headers['x-uploadedfilename']}`;
fs.writeFile(to, fileData, (err) => {
if (err) { throw err; }
console.log('Saved file to ' + to);
res.end();
});
});
}
}).listen(8080);
示例6: handleUpload
function handleUpload(req:IncomingMessage, res:ServerResponse, jpgFile, token) {
if (!checkToken(jpgFile, token, process.env.SECRET)) {
console.log("wrong_token");
res.end(JSON.stringify({ok: false, error: "wrong_token"}));
return;
}
var form = new formidable.IncomingForm();
form.maxFields = 1;
form.uploadDir = "/tmp_files";
form.parse(req, (err, fields:Fields, files:Files)=> {
if (!files) {
res.end(JSON.stringify({ok: false, error: "no_file_data"}));
}
var file = files["file"];
var tmpPath = file.path;
var subDir = makeSubpath(token);
var newDir = '/thumbs/' + subDir;
var newPath = newDir + "/" + jpgFile;
fs.exists(newDir, (exists:boolean)=> {
if (!exists) {
// console.log("Folder " + newDir + " not exist");
mkdirp(newDir, (err)=> {
if (err) {
res.end(JSON.stringify({ok: false, error: "cant_create_subdir"}));
console.error(err);
} else {
moveFile(tmpPath, newPath);
}
});
} else {
moveFile(tmpPath, newPath);
}
});
res.writeHead(200, {'content-type': 'text/plain'});
res.end(JSON.stringify({ok: true, url: subDir + "/" + jpgFile}));
});
form.on('error', (err)=> {
console.error(err);
});
}
示例7: function
app.post('/api/document-upload', function (request, response) {
var form = new formidable.IncomingForm();
form.parse(request, function (err, fields, files) {
console.log('inspect:\n', util.inspect({ fields: fields, files: files }));
console.log('filename: ', files.file.name);
});
form.on('progress', function (bytesReceived, bytesExpected) {
var percent_complete = (bytesReceived / bytesExpected) * 100;
console.log(percent_complete.toFixed(2));
});
form.on('error', function (err) {
err ? httpError(HTTP_ServerError, err, response) : httpOk(response);
});
form.on('end', function (fields, files) {
/* Temporary location of our uploaded file */
var temp_path = this.openedFiles[0].path;
var file_name = this.openedFiles[0].name;
GridFS.saveFileToDb(this.openedFiles[0].path, this.openedFiles[0].name, 'document', null)
.then(function () { httpOk(response); })
.catch(function (err) { httpError(HTTP_ServerError, err, response); });
});
});
示例8: function
index.post('/', function(req, res, next) {
if (req.method.toLowerCase() == 'post') {
var uploadObj = { "title" : null, "description" : null, "url" : null};
var fmr = new frd.IncomingForm();
fmr.parse(req, function (err, fields, files) {
res.writeHead(200, { 'content-type': 'text/plain' });
uploadObj.title = fields.title;
uploadObj.description = fields.description;
});
fmr.on('end', function (fields, files) {
var tempPath = this.openedFiles[0].path;
var fileName = this.openedFiles[0].name;
var newFileName = "//D-113077851/GopikrishnaShare/PSPMarketPlace/"+ fileName;
uploadObj.url = newFileName;
filestore.copy(tempPath, newFileName, function (err) {
if (err) {
console.error(err);
} else {
var obj = new uploadModule();
obj.insertDocument(uploadObj)
.then(function(result){
res.end(JSON.stringify(result));
});
}
});
});
return false;
}
});
示例9: IncomingForm
.then((data: IContent) => {
if (data) {
let form: IncomingForm = new IncomingForm(),
formData: any = {
type: CONST.IMAGE_TYPES.PHOTO,
path: path.join(root,data._id.toString())
},
log: any = {
creator,
creatorRef,
target: data._id,
targetRef: req.routeVar.contentType,
action: CONST.USER_ACTIONS.COMMON.UPLOAD,
ua: req.body.ua || req.ua
}
form.multiples = true
form
.on('file', (fields: Fields, file: any) => {
let fileName = UTIL.renameFile(file.name),
key = fileName.substring(0, fileName.lastIndexOf('.'))
formData[key] = {
value: fs.createReadStream(file.path),
options: {
filename: UTIL.renameFile(file.name)
}
}
})
.on('end', () => {
request
.post({
url: SERVERS.UPLOAD_SERVER,
formData
}, (err: Error, response, body) => {
if (err) console.log(err)
let gallery: any[] = data.gallery || [],
fileList = JSON.parse(body).files
fileList.forEach((m: IMedia) => {
gallery.push(m)
})
DataModel
.findByIdAndUpdate(data._id, {gallery}, {new: true})
.then((updated: IContent) => {
res.status(201).json(updated)
new Logger(log)
})
})
})
.on('error', (err: Error) => {
console.log(err)
})
form.parse(req)
} else {
res.status(404).send()
}
})