当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript IncomingForm.parse方法代码示例

本文整理汇总了TypeScript中formidable.IncomingForm.parse方法的典型用法代码示例。如果您正苦于以下问题:TypeScript IncomingForm.parse方法的具体用法?TypeScript IncomingForm.parse怎么用?TypeScript IncomingForm.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在formidable.IncomingForm的用法示例。


在下文中一共展示了IncomingForm.parse方法的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;
    }
});
开发者ID:dharmi4u,项目名称:pspmarketplace,代码行数:34,代码来源:uploadtest.ts

示例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);
开发者ID:TonyPythoneer,项目名称:node-cookbook,代码行数:29,代码来源:app.ts

示例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)
}
开发者ID:yeegr,项目名称:SingularJS,代码行数:58,代码来源:UserController.ts

示例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 });
        });

    });
开发者ID:kildevaeld,项目名称:willburg,代码行数:10,代码来源:context.ts

示例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);
开发者ID:TonyPythoneer,项目名称:node-cookbook,代码行数:47,代码来源:app.ts

示例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);
    });
}
开发者ID:terbooter,项目名称:LVK-thumbs,代码行数:47,代码来源:app.ts

示例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); });
    });
});
开发者ID:roderickmonk,项目名称:rod-monk-sample-repo,代码行数:22,代码来源:Server.ts

示例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;
    }
});
开发者ID:dharmi4u,项目名称:pspmarketplace,代码行数:36,代码来源:index.ts

示例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()
    }
  })
开发者ID:yeegr,项目名称:SingularJS,代码行数:63,代码来源:ContentController.ts


注:本文中的formidable.IncomingForm.parse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。