SHARE
TWEET

upload.js

a guest Oct 6th, 2017 197 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 参考サイト,http://blog.sarabande.jp/post/30694191998
  2. // 引数のBase64の文字列をBlob形式にしている
  3. var base64ToBlob = function(base64){
  4.     var base64Data = base64.split(',')[1], // Data URLからBase64のデータ部分のみを取得
  5.         data = window.atob(base64Data), // base64形式の文字列をデコード
  6.         buff = new ArrayBuffer(data.length),
  7.         arr = new Uint8Array(buff),
  8.         blob, i, dataLen;
  9.    
  10.     // blobの生成
  11.     for( i = 0, dataLen = data.length; i < dataLen; i++){
  12.         arr[i] = data.charCodeAt(i);
  13.     }
  14.     blob = new Blob([arr], {type: 'image/png'});
  15.     return blob;
  16. }
  17.  
  18. //ファイル名の取得
  19. //参考サイト,http://write-remember.com/program/javascript/input_type_file/
  20. function getFileName() {
  21.     var bufstr = document.getElementById("imgfile").value;
  22.     var regex = /\\|\\/;
  23.     var array = bufstr.split(regex);
  24.     return array[array.length - 1];
  25. }
  26.  
  27. function send(formElem){
  28.     var canvasElem = document.getElementById('imgcanvas');
  29.     var canvasblob = base64ToBlob(canvasElem.toDataURL());    
  30.     var formData = new FormData(formElem);
  31.     formData.append('imgfile', canvasblob, getFileName());
  32.     $.ajax({
  33.         type: 'POST',
  34.         url: 'upload.php',
  35.         data: formData,
  36.         contentType: false,
  37.         processData: false,
  38.     }).done(function(responseData, status, jqXHR) {
  39.         alert(responseData);
  40.         location.reload();
  41.     }).fail(function(responseError, status, errorThrown) {
  42.         alert(responseError);
  43.         location.reload();
  44.     });
  45. }
  46.  
  47. //フォームが送信される時に実行する処理
  48. document.getElementById('postform').addEventListener('submit', function (e) {
  49.     //フォームの要素を取得
  50.     formElem = this;
  51.     //フォームの送信をキャンセル
  52.     e.preventDefault();
  53.     //POST
  54.     send(formElem);
  55. }, false);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top