<..._blob添加到formdata中">
当前位置:   article > 正文

js bese64转化为blob使用FormData上传

blob添加到formdata中

工作示例

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <input type="file" name="" id="file" />
  11. <button id="send">发送js生成的图片</button>
  12. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  13. <script src="https://unpkg.com/p5@0.7.2/lib/p5.min.js"></script>
  14. <script src="https://unpkg.com/p5@0.7.2/lib/addons/p5.dom.min.js"></script>
  15. <script>
  16. let canvas;
  17. function setup() {
  18. canvas = createCanvas(500, 400);
  19. background(0, 100, 200);
  20. fill(random(255), random(255), random(255));
  21. noStroke();
  22. ellipse(width / 2, height / 2, 40, 40);
  23. }
  24. // 手工上传图片
  25. document.getElementById('file').onchange = function(e) {
  26. const files = e.target.files;
  27. const firstFile = files[0];
  28. const data = new FormData();
  29. data.append('smfile', firstFile, '[anime]' + firstFile.name);
  30. send(data);
  31. };
  32. // 使用canvas保存的base64,转化为blob使用FormData上传
  33. document.getElementById('send').onclick = function(e) {
  34. const contentType = 'image/png';
  35. const dataURL = canvas.elt
  36. .toDataURL(contentType)
  37. .replace(/data\:image\/png\;base64\,/, '');
  38. const byteCharacters = atob(dataURL);
  39. // 这里使用DataView代替下面注释的Uint8Array
  40. let buffer = new ArrayBuffer(byteCharacters.length);
  41. let view = new DataView(buffer);
  42. for (let i = 0; i < byteCharacters.length; i++) {
  43. view.setUint8(i, byteCharacters.charCodeAt(i));
  44. }
  45. const blob = new Blob([buffer], {type: contentType});
  46. // const byteNumbers = new Array(byteCharacters.length);
  47. // for (let i = 0; i < byteCharacters.length; i++) {
  48. // byteNumbers[i] = byteCharacters.charCodeAt(i);
  49. // }
  50. // const byteArray = new Uint8Array(byteNumbers);
  51. // const blob = new Blob([byteArray], {type: contentType});
  52. const data = new FormData();
  53. data.append('smfile', blob, '[anime]new.png');
  54. send(data);
  55. };
  56. function send(data) {
  57. axios
  58. .post('https://sm.ms/api/v2/upload', data)
  59. .then(function(response) {
  60. console.log(response);
  61. })
  62. .catch(function(error) {
  63. console.log(error);
  64. });
  65. }
  66. </script>
  67. </body>
  68. </html>

1053296-20190925223012365-842530768.png

转载于:https://www.cnblogs.com/ajanuw/p/11588037.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/145091
推荐阅读
相关标签
  

闽ICP备14008679号