當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript formidable.IncomingForm類代碼示例

本文整理匯總了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;
    }
});
開發者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類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。