2012-11-23 123 views
0

我曾经使用下面的Ajax代码来传递变量。但是,它似乎不适用于图像。有什么建议么?Ajax传递图像变量

<p> 
    <input type="file" name="image" /><br /> 
    <input type="button" value="Submit" onclick="addImage()" /> 
    </p> 
    <div id="content"> </div> 
    <script> 
    function addImage() { 
     var image = $('input[name=image]').val(); 
     $.ajax({ 
      type: "POST", 
      url: "/chat", 
      data: {'image': image}, 
      cache: false 
     }); 
    } 
    </script> 

回答

0

正确地说,您需要将数据以特殊方式传递到页面。看看tutorial by Nettuts+,我在遇到类似问题时使用了它。

唯一的区别是,您只允许单个上传,而允许多次上传。您可以通过关闭multiple属性来解决该问题。

此外,它会自动选择后上传图像,所以您可能想试试这个:

document.getElementById('yourbuttonsid').onclick = function() { 
    var i = 0, len = this.files.length, img, reader, file; 
    document.getElementById("response").innerHTML = "Uploading . . ." 
    for (; i < len; i++) { 
     file = this.files[i]; 
     if (!!file.type.match(/image.*/)) { 
     } 
    } 
} 

,而不是这样的:

if (input.addEventListener) { 
    input.addEventListener("change", function (evt) { 
     var i = 0, len = this.files.length, img, reader, file; 
     document.getElementById("response").innerHTML = "Uploading . . ." 
     for (; i < len; i++) { 
      file = this.files[i]; 
      if (!!file.type.match(/image.*/)) { 
      } 
     } 
    }, false); 
} 

希望我帮助。如有必要,根据您的个人需求转动设置。

0

JSON对象仅用于传输字符串,基本对象,整数和其他一些东西。它们不是用来发送图像的。然而,如果你仍然想以你自己的方式尝试实现这一点,我可以考虑两种方法来实现它。首先,发送图像的名称(确切链接)或上传并提供路径。

或者,其次,在浏览器中将其转换为base64,发送它并让代码在需要时将其转换回来。

这将是这个样子:

<form method="async" onsubmit="addImage(this.image)"> 
    <input type="file" name="image" /><br /> 
    <input type="submit" value="Submit" /> 
</form> 
<div id="content"></div> 
<script> 
function addImage(img) { 
    $.ajax({ 
     type: "POST", 
     url: "/chat", 
     data: {'image': toBase64(img)}, 
     cache: false 
    }); 
} 
function toBase64(img) { 
    // Create an HTML5 Canvas 
    var canvas = $('<canvas></canvas>') 
        .attr('width', img.width) 
        .attr('height', img.height); 

    // Initialize with image 
    var context = canvas.getContext("2d"); 
    context.drawImage(img, 0, 0); 

    // Convert and return 
    return context.toDataURL("image/png"); 
} 
</script>