提问者:小点点

如何为ajax post附加一个带有base 64字符串的隐藏输入值


我需要帮助,我试图追加一个隐藏的输入类型,从一个java脚本库负责应用过滤器到我的图像的形式。随着onClick事件,我附加一个输入类型隐藏的base64字符串的值到页面上的表单。然后当我提交表单时,它应该提交数据到表单数据中,然后php应该将base64转换为img文件并保存它。然而,当我尝试回显$img它的空白时,它没有收到字符串。因此,保存的图像有0个字节。我不太确定为什么,因为我所做的只是附加一个隐藏值,该值设置为base64字符串。

Script. Js这是负责将过滤器应用于图像的文件,这是在应用过滤器之后,我正在使用base64字符串编码将隐藏值附加到profile.html页面表单。

if( effect in this){
    this[effect]();
    this.render();
    var img_send = clone[0].toDataURL("image/png;base64;");
    $('<input/>').attr({type: 'hidden', id: 'fileroast', value: img_send}).appendTo('#output');
}
else{
    hideDownload();
}

PHP5上传脚本base64字符串到img

<?php
    // requires php5
    define('UPLOAD_DIR', 'images/profile_images/');
    $img = $_POST['fileroast'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.png';
    $success = file_put_contents($file, $data);
    print $success ? 'default':'images/profile_images/default.png';
?>

超文本标记语言Profile. HTML主页Ajax调用:

      //upload profile picture
    function submitForm() {
      if(get_user != logged_username){
        }else{
        var d = new Date();
        var time = d.getTime();
        var fd = new FormData(document.getElementById("fileinfo"));
        $.ajax({
          url: "upload_photo.php",
          type: "POST",
          data: fd,
          enctype: 'multipart/form-data',
          processData: false,  // tell jQuery not to process the data
          contentType: false   // tell jQuery not to set contentType
        }).done(function( data ) {
            if (data.indexOf("Invalid") >= 0) { 
                alert('invalid file type, must be jpeg, jpg, or png.');
            }else{
              console.log(data);
              var post = {"pic_location":data, "time":time, "username": logged_username};
              console.log(post);
              var json_data = post;
              Cynergi.insert('http://.com:3000/profile_pictures', json_data);
            }
        });
        return false;
    }
   }

超文本标记语言Profile. HTML上传模态表单html.

<div id="uploadPic" class="modal fade" >
  <form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header" style="background:#f3f3f3;">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" style="color:black;">Choose picture to upload as profile pic.</h4>
            </div>
            <div class="modal-body">
              <div id="photo">
                <a href="#" class="downloadImage" target="_blank" download="photo.png">Download Image</a>-
              </div>
              <div id="filterContainer" style='width:400px;'>
                <ul id="filters" style='width:400px;'>
                  <li> <a href="#" id="normal">Normal</a> </li>
                  <li> <a href="#" id="vintage">Vintage</a> </li>
                  <li> <a href="#" id="lomo">Lomo</a> </li>
                  <li> <a href="#" id="clarity">Clarity</a> </li>
                  <li> <a href="#" id="sinCity">Sin City</a> </li>
                  <li> <a href="#" id="sunrise">Sunrise</a> </li> 
                  <li> <a href="#" id="crossProcess">Cross Process</a> </li>
                  <li> <a href="#" id="orangePeel">Orange Peel</a> </li>
                  <li> <a href="#" id="love">Love</a> </li>
                  <li> <a href="#" id="grungy">Grungy</a> </li>
                  <li> <a href="#" id="jarques">Jarques</a> </li>
                  <li> <a href="#" id="pinhole">Pinhole</a> </li>
                  <li> <a href="#" id="oldBoot">Old Boot</a> </li>
                  <li> <a href="#" id="glowingSun">Glowing Sun</a> </li>
                  <li> <a href="#" id="hazyDays">Hazy Days</a> </li>
                  <li> <a href="#" id="herMajesty">Her Majesty</a> </li>
                  <li> <a href="#" id="nostalgia">Nostalgia</a> </li>
                  <li> <a href="#" id="hemingway">Hemingway</a> </li>
                  <li> <a href="#" id="concentrate">Concentrate</a> </li>
                </ul>
              </div>
              <div id='output_file'></div>
              <div id="output"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <input type="submit" value="Upload" class="btn btn-info" data-dismiss="modal" onClick="return submitForm();"/> 
            </div>
        </div>
    </div>
  </form>
</div>

Http请求检查器:

Remote Address:
Request URL:http://thewaywardjourney.com/upload_photo.php
Request Method:POST
Status Code:200 OK
Response Headers
view source
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html
Date:Tue, 05 May 2015 22:25:11 GMT
Server:nginx/1.4.6 (Ubuntu)
Transfer-Encoding:chunked
X-Powered-By:PHP/5.5.9-1ubuntu4.7
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:44
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryWxBLMFLj0klea1td
Cookie:token=00; username=00; getuser=000
Host:thewaywardjourney.com
Origin:http://thewaywardjourney.com
Referer:http://thewaywardjourney.com/profile.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
------WebKitFormBoundaryWxBLMFLj0klea1td--

varimg_send=clone[0]. toDataURL("image/png;base64;"); $('').attr({type:'隐藏',id:'fileroast',value:inkdeURIComponent(img_send)}).appendTo('#输出');

console.log(decodeURIComponent($('#fileroast').val()));

输出:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0CAYAAADL1t+KAAAgAElEQ…P3PeerM0GN4J7vE4xyTdlT34hvfOMbuiYnL6xlqkUu4v8BZ033tp7lXCwAAAAASUVORK5CYII=

console.log($('#fileroast').val());

输出:

data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhEUgAAAfQAAAH0CAYAAADL1t%2BKAAAgAElEQVR4Xsy9CbhlV1UtPPbep2%2FuuX1%2Fq29SVan0gUAU8AEJSYCQIEhoQoAISE9QQJSHIsIDBeX5sHkqSuOPD39EMCBBBRII6WlNX33VvVW3P%2F3Z%2Ff6%2FMdde5%2B57qkmQxPef%2Buq73Tm7WXutOeYcc8y5jK985HVRFEaIogimacIwDBimCXlFEbwwgGGZMA3%2BN4Awkt8b6h2IAARY%2Byz4nihCEARyLNOyEIVh%2FO5Tf0kZ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V28v38Rj8G79vt9tIp9PI5wtoNBrIZjPK7nNADdpbH5bFcY%2Fgug6KxaKcL2l3eBzX9ZBJFxCGaq5pW9S12XyWRgBeOs%2FP%2F7xfnptzm9%2FzmtPprBxf3WOIMFL2IJ22sGXrdnz%2BC19Dcont....

这是我的php:

<?php

    // requires php5

    define('UPLOAD_DIR', 'images/profile_images/');

    $img = $_POST['fileroast'];



    function base64url_decode($data) { 

      return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT)); 

    } 



    $img_ret = base64url_decode($img);

    print $img_ret;

    $img = str_replace('data:image/png;base64,', '', $img_ret);

    $img = str_replace(' ', '+', $img_ret);

    $data = base64_decode($img_ret);

    $file = UPLOAD_DIR . uniqid() . '.png';

    $success = file_put_contents($file, $data);

    print $data . $file;

    //print $success ? 'default':'images/profile_images/default.png';

?>

共1个答案

匿名用户

Base64字符集有一个和/所以字符串必须是urlencoded。

>

  • 右键单击浏览器窗口,

    检查元素、网络选项卡、

    “全部”改为XHR,提交数据,

    “表单数据”选择“查看来源”。

    它将显示在AJAXHTTP请求中提交的任何数据。