zoukankan      html  css  js  c++  java
  • node.js form 上传

    安装formidable
    pm install formidable@latest

    客户端表单提交
    <form class="form-signin" role="form" method="post" enctype='multipart/form-data'>
            <h2 class="form-signin-heading">上传文件</h2>
            <input id="fulAvatar" name="fulAvatar" type="file" class="form-control" />     
            <br/>
            <button id="btnSub" class="btn btn-lg btn-primary" type="submit">上 传</button>
          </form>
    服务端指定路由规则
    router.post('/upload', function(req, res) {
    
      var form = new formidable.IncomingForm();   //创建上传表单
          form.encoding = 'utf-8';        //设置编辑
          form.uploadDir = 'public' + AVATAR_UPLOAD_FOLDER;     //设置上传目录
          form.keepExtensions = true;     //保留后缀
          form.maxFieldsSize = 2 * 1024 * 1024;   //文件大小
    
        form.parse(req, function(err, fields, files) {
             if (err) {
              res.locals.error = err;
              res.render('index', { title: 'TITLE' });
              return;        
            }  
           
            console.log(fields);
    
            var extName = '';  //后缀名
            switch (files.fulAvatar.type) {
                case 'image/pjpeg':
                    extName = 'jpg';
                    break;
                case 'image/jpeg':
                    extName = 'jpg';
                    break;         
                case 'image/png':
                    extName = 'png';
                    break;
                case 'image/x-png':
                    extName = 'png';
                    break;         
            }
    
            if(extName.length == 0){
                  res.locals.error = '只支持png和jpg格式图片';
                  res.render('index', { title: TITLE });
                  return;                   
            }
    
            var avatarName = Math.random() + '.' + extName;
            var newPath = form.uploadDir + avatarName;
    
            console.log(newPath);
            fs.renameSync(files.fulAvatar.path, newPath); 
        });
    
        res.render('upload', { title: 'Upload Demo' });      
    });
    View Code
  • 相关阅读:
    android调用系统拍照那些事
    HttpClient4.5
    关于Android自带的定位处理
    ORMLite配置异常处理
    mysql绿色版配置
    android 震动和提示音
    Weblogic新增域(可以配置新端口)
    weblogic启动错误
    将程序部署到weblogic出现乱码问题
    SVN更新报错
  • 原文地址:https://www.cnblogs.com/wangxm123/p/4192189.html
Copyright © 2011-2022 走看看