1. 程式人生 > 實用技巧 >表單上傳檔案,後臺通過formidable處理上傳檔案

表單上傳檔案,後臺通過formidable處理上傳檔案

使用表單上傳檔案

  1. 通過表單上傳檔案

    <form class="form-horizontal" role="form"
        enctype="multipart/form-data" method="POST"
        action="/contest/vacation-photo/{{year}}/{{month}}">
      <div class="form-group">
        <label for="fieldName" class="col-sm-2 control-label">Name</label>
        <div class="col-sm-4">
            <input type="text" class="form-control"
            id="fieldName" name="name">
        </div>
      </div>
      <div class="form-group">
         <label for="fieldEmail" class="col-sm-2 control-label">Email</label>
          <div class="col-sm-4">
              <input type="email" class="form-control" required
                id="fieldEmail" name="email">
          </div>
      </div>
      <div class="form-group">
          <label for="fieldPhoto" class="col-sm-2 control-label">Vacation photo
          </label>
          <div class="col-sm-4">
              <input type="file" class="form-control" required accept="image/*"
                id="fieldPhoto" name="photo">
          </div>
      </div>
      <div class="form-group">
          <div class="col-sm-offset-2 col-sm-4">
              <button type="submit" class="btn btn-primary">Submit</button>
          </div>
      </div>
    </form>
    

    必須指定:enctype="multipart/form-data" 來告訴瀏覽器要上傳檔案

如何上傳圖片

<input type="file" required accept="image/*" name="photo">
  • type: 規定輸入框型別
  • accept: 規定通過檔案上傳上傳的檔案型別 "image/*"表示上傳圖片型別--但是我上傳docx文件也不會報錯的呀
  • name: 傳送請求時傳給伺服器的欄位

後臺通過formidable處理上傳檔案

var formidable = require('formidable')

...

// year和month是怎麼渲染的
app.post('/contest/vacation-photo/:year/:month', (req, res) => {
  var now = Date.now()

  var form = new formidable.IncomingForm({
    multiples: true,
    // 3.設定上傳檔案的儲存目錄
    // uploadDir: __dirname +  '/public/imgs'
  })

  // 2.設定編碼:如果有普通鍵值對資料就最好設定
  // form.encoding = 'utf-8'

  // 3.設定上傳檔案的儲存目錄  -- 之前把路徑寫成  __dirname +  'public/imgs'  老報錯Emmit
  form.uploadDir =  __dirname +  '/public/imgs'

  // 4.設定是否保留檔案的副檔名 --若不保留檔案的額副檔名,在服務端儲存的就是隻有檔名沒有副檔名的未知檔案,
       // 如圖片:upload_5bb718ac0c1ec3bb318742bcd102a151
  form.keepExtensions = true

  form.parse(req, function(err, fields, files){
    if(err) return res.redirect(303, '/html/error.html');
    console.log('received fields:');
    console.log(fields);   // { name: '張三丰', email: '[email protected]' }
    console.log('received files:');
    console.log(files);   // 上傳的圖片物件
    res.json({ fields, files })
    // res.redirect(303, '/html/thank-you.html');
  })
})