兩種 主流 上傳 圖片 方法 jquery+multer jquery multer 原生 欄目 JQuery 简体版
原文   原文鏈接

原文首發:https://shuirong.github.io/
博主通過實踐,這裏給出兩種處理用戶上傳圖片的方法,先後端代碼皆有.javascript

1. 前端jQuery,後端Express的Multer中間件html

index.html前端

<!--index.html-->
<img id="preview"  alt="" />
<form method="post" id='picForm' enctype="multipart/form-data" action='/update'>
    <input type="file" name="avatar" onchange="deal()">
    <button type="submit">提交</button>
</form>

fontend.jsjava

function deal(){
    let file = new FormData(document.getElementById("picForm"));
    file.append("CustomField", "This is some extra data");
    $.ajax({
      url: "/update",
      type: "POST",
      data: file,
      processData: false,  /* 告訴jQuery不要去處理髮送的數據*/
      contentType: false   /* 告訴jQuery不要去設置Content-Type請求頭*/
    });
}

backend.jsgit

/*後端代碼:用express初始化項目以後,新建一個路由文件.路由update. update.js */
var express = require('express');
var router = express.Router();
var multer = require('multer');
var upload = multer({
    dest: 'uploads/' /*設置上傳的圖片/文件存放的地方爲根目錄下的uploads文件夾*/
});

/*single(fieldName) 中的fieldName必須和HTML中input的屬性name的值同樣*/
router.post("/",upload.single('avatar'),function(req,res,next) {
    console.log(req.file); /* req.file 是 `logo` 文件的信息*/
      console.log(req.body); /* req.body 保存表單文本域數據, 若是存在的話*/
    res.send('Upload Done !');
});

module.exports = router;

多圖片上傳github

和單圖上傳並預覽基本一個套路.ajax

<!--index.html, 預覽功能不說了,單圖預覽懂了,多圖就會了-->
<form method="post" enctype="multipart/form-data" action='/update'>
    <input type="file" name="avatars">
      <input type="file" name="avatars">
      <input type="file" name="avatars">
    <button type="submit">提交</button>
</form>
/*其餘地方和上面的同樣. update.js*/
router.post("/",upload.array('avatars',3),function(req,res,next) {
    console.log(req.files); /* req.files 是 `avatars` 文件數組的信息*/
      console.log(req.body); /* req.body 保存表單文本域數據, 若是存在的話*/
    res.send('Upload Done !');
});

2. 先後端皆原生JSexpress

前端把圖片轉換成base64格式,後端再轉成二進制數據(存成圖片)json

index.html後端

<input type='file' ref='files' onchange='inputChange' id='uploadImg'>

fontend.js

inputChange(e) {
  const files = e.target.files[0];
  const reader = new FileReader();
  reader.onload = (ee) => {
    const data = {
      base64: ee.target.result,
    };
    post(this.uploadUrl, data).then((res) => {
      // 根據返回數據作些處理.
    }).catch((err) => {
      console.info('Error', err);
    });
  };
  reader.readAsDataURL(files);
}

/* 這裏把xhr的post給封裝了 */
post(url, data) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304)) {
          resolve(JSON.parse(xhr.responseText));
        } else {
          reject(`XHR unsuccessful:${xhr.status}`);
        }
      }
    };
    xhr.open('post', url, true);
    xhr.setRequestHeader('content-type', 'application/json');
    xhr.send(JSON.stringify(data));
  });
}

backend.js

const express = require('express');
const router = express.Router();
const fs = require('fs');

router.route('/')
    .post(upload.single('image'), (req, res) => {
        let base64 = req.body.base64;
        //去掉base64數據最前面的"圖片類型"字符串
        let type = base64.match(/^data:image\/(.+);/)[1];
        base64 = base64.replace(/^data:image\/\w+;base64,/, "");
        // 解碼base64成二進制數據.
        let data = new Buffer(base64, 'base64');
        const name = `uploads/images/${String(new Date()).replace(/[ :]/g,'').match(/.{6}(.{12})/)[1]}.${type}`;
        fs.open(name, "a", 0644, function(e, fd) {
            if (e) throw e;
            fs.write(fd, data, function(e) {
                if (e) throw e;
                fs.closeSync(fd);
                res.json({
                    'path': name.replace('uploads', ''),
                });
            });
        });

    });

module.exports = router;

PS:  關於美化文件上傳按鈕,一個思路就是設置input的opacity爲0,而後在外面包裹一個div.

PPS: CSS的奇技淫巧仍是不少的.

相關文章
相關標籤/搜索
每日一句
    每一个你不满意的现在,都有一个你没有努力的曾经。
本站公眾號
   歡迎關注本站公眾號,獲取更多信息