【问题标题】:upload images with php through javascript通过javascript用php上传图片
【发布时间】:2014-12-22 22:38:07
【问题描述】:

carica.html

<td>
    <input type="file" size="30" onchange="preview()" id="upload_immagine">
</td>
<td>
    <div id="divImmagine" > </div>
</td>

文件javascript.js

function preview() 
{
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
            document.getElementById("divImmagine").innerHTML=xmlhttp.responseText;
    }
    image=request.getParameter("upload_immagine");
    document.getElementById("divImmagine").innerHTML=image;
    xmlhttp.open("POST","stampaAnteprima.php", false);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("image="+image);
}

stampaAnteprima.php

<?php
    $file_temp=($_FILES['image']['tmp_name']);
    echo"$file_temp";
?>

javascript image=request.getParameter("upload_immagine"); 行不返回任何内容。如何获取传递给 php 的值,然后通过 $_FILES['image']['tmp_name'] 读取文件,实际上它是图像?你有什么建议吗?

【问题讨论】:

  • 标准 ajax 不允许文件上传。
  • 使用 jquery 的 malsups 文件上传插件链接:malsup.com/jquery/form
  • 另一个好的解决方案是:fineuploader.com
  • @MarcB 您必须更清楚“标准 ajax”是什么。就目前而言,除了 IE9 和更早版本之外的所有浏览器都允许通过 XHR 上传文件。

标签: javascript php html ajax ajaxform


【解决方案1】:

这将允许您将文件发送到 php.ini。

您可以添加更多事件监听器来显示上传进度和错误处理。

function UploadPhoto(){
    var file = document.getElementById('upload_immagine').files[0];
    var formdata = new FormData();
    formdata.append("image", file);
    var req = new XMLHttpRequest();
    req.addEventListener("load", function(event) { uploadcomplete(event); }, false);
    req.open("POST", "stampaAnteprima.php");
    req.send(formdata);
}
function uploadcomplete(event){
// Your php reply = event.target.responseText 
}

【讨论】:

    猜你喜欢
    • 2013-05-07
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    相关资源
    最近更新 更多