Formidable文件上传

这是一个使用formidable模块实现单个文件上传的案例。再次记录一下

step1: 进入workspace, 执行 

express -e fmp
cd fmp
npm install
npm install formidable --save

step2: 修改index.ejs

//index.ejs

<!DOCTYPE html>
<html>
  <head>
    <title>文件上传</title>
    <style type="text/css">
      .upload-button {

      }

      .upload-box {
        display: none;
      }

      .upload-info {
        display: none;
      }

      .upload-box label {
        width: 50px;
        display: inline-block;
      }

    </style>
  </head>
  <body>
    <h1>文件上传</h1>
    <button class="upload-button" id="showUpload">点击上传</button>
    <div class="upload-box" id="fileUploadFrom">
      <label for="name">Name</label>
      <input type="text" name="name" id="name"/><br/>
      <label for="file">File</label>
      <input type="file" name="file" id="file"/><br/>
      <button id="upload">Upload</button>
    </div>
    <div class="upload-info">
      <progress value="0" max="100"></progress>
      <span class="progress-value">0</span>
    </div>
  </body>

  <script type="text/javascript" src="/jquery/dist/jquery.js"></script>
  <script type="text/javascript" src="/javascripts/file.js"></script>
</html>

step3: 在public/javascripts/下创建file.js

// file.js

$(document).ready(function() {

  $('#showUpload').on('click', function(e) {
    $('.upload-box').show(300);
  });

  $('#upload').on('click', function(e) {
    var formData = new FormData();
    formData.append('file', $('#file').prop('files')[0]);
    formData.append('name', $('#name').val());
    $.ajax({
      url: "/files/upload",
      cache: false, //设置为 false 将不会从浏览器缓存中加载请求信息
      contentType: false, //(默认: "application/x-www-form-urlencoded") 发送信息至服务器时内容编码类型
      processData: false, //默认情况下,发送的数据将被转换为对象(技术上讲并非字符串) 以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。
      data: formData,
      type: 'post',
      xhr: function() {
        var myXhr = $.ajaxSettings.xhr();
        if(myXhr.upload){ // Check if upload property exists
        myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload
        }
        return myXhr;
      },
      beforeSend: function() {
        $('.upload-info').show();
      },
      success: function(xhr) {
        console.log(xhr);
      },
      error: function(err) {
        console.log('error');
      }
    })
  });

  var $progressValue = $('.progress-value');
  var $progressBar = $('progress');
  function progressHandlingFunction(e) {
    if(e.lengthComputable){
      console.log('value = ' + e.loaded + ', total = ' + e.total);
      var value = Math.floor(e.loaded/e.total * 100);
      $progressBar.val(value)
      $progressValue.text(value + '%');
    }
  };

});

step4: 编写 /router/index.js模块

var config = require('../config');
var express = require('express');
var router = express.Router();
var formidable = require('formidable');

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'Express' });
});

router.post('/files/upload', function(req, res, next) {
  var form = formidable.IncomingForm();
  form.encoding = 'utf-8';
  form.uploadDir = config.uploadDir;
  form.keepExtensions = true;
  // form.maxFieldsSize = 2 * 1024 * 1024; // 单位为byte

  form.on('progress', function(bytesReceived, bytesExpected) {
    var progressInfo = {
      value: bytesReceived,
      total: bytesExpected
    };
    console.log('[progress]: ' + JSON.stringify(progressInfo));
    res.write(JSON.stringify(progressInfo));
  }); 

  form.on('end', function() {
    console.log('end'); 
    res.end('success');
  });

  form.on('error', function(err) {
    console.error('upload failed', err.message);
    next(err);
  })

  form.parse(req);
});

module.exports = router;

step5: 启动项目 npm start

在浏览器输入 http://localhost:3000/,就可以测试啦!



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值