js bese64转化为blob使用FormData上传

工作示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <input type="file" name="" id="file" />
    <button id="send">发送js生成的图片</button>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://unpkg.com/p5@0.7.2/lib/p5.min.js"></script>
    <script src="https://unpkg.com/p5@0.7.2/lib/addons/p5.dom.min.js"></script>
    <script>
      let canvas;
      function setup() {
        canvas = createCanvas(500, 400);
        background(0, 100, 200);

        fill(random(255), random(255), random(255));
        noStroke();
        ellipse(width / 2, height / 2, 40, 40);
      }

      // 手工上传图片
      document.getElementById('file').onchange = function(e) {
        const files = e.target.files;
        const firstFile = files[0];

        const data = new FormData();
        data.append('smfile', firstFile, '[anime]' + firstFile.name);
        send(data);
      };

      // 使用canvas保存的base64,转化为blob使用FormData上传
      document.getElementById('send').onclick = function(e) {
        const contentType = 'image/png';
        const dataURL = canvas.elt
          .toDataURL(contentType)
          .replace(/data\:image\/png\;base64\,/, '');
        const byteCharacters = atob(dataURL);
        
        // 这里使用DataView代替下面注释的Uint8Array
        let buffer = new ArrayBuffer(byteCharacters.length);
        let view = new DataView(buffer);
        for (let i = 0; i < byteCharacters.length; i++) {
          view.setUint8(i, byteCharacters.charCodeAt(i));
        }
        const blob = new Blob([buffer], {type: contentType});

        // const byteNumbers = new Array(byteCharacters.length);
        // for (let i = 0; i < byteCharacters.length; i++) {
        //   byteNumbers[i] = byteCharacters.charCodeAt(i);
        // }
        // const byteArray = new Uint8Array(byteNumbers);
        // const blob = new Blob([byteArray], {type: contentType});

        const data = new FormData();
        data.append('smfile', blob, '[anime]new.png');
        send(data);
      };

      function send(data) {
        axios
          .post('https://sm.ms/api/v2/upload', data)
          .then(function(response) {
            console.log(response);
          })
          .catch(function(error) {
            console.log(error);
          });
      }
    </script>
  </body>
</html>

posted @ 2019-09-25 22:20  Ajanuw  阅读(1693)  评论(0编辑  收藏  举报