小编典典

使用Ajax将图片传递到PHP

ajax

我试图将图像和标题字段值传递给PHP,通常我会使用$ _FILES数组直接用PHP处理文件上传,但我不确定如何使用ajax将其创建/传递给PHP。我的表格:

<form role="form" name="updateProductForm" id="updateProductForm" method="POST" enctype="multipart/form-data"> 
    <input name="imgOne" id="imgOne" type="file" title="Add Image">
    <a class="btn btn-primary" name="updateProduct" id="updateProduct">Update Product</a></div>
</form>

我正在尝试使用它传递给PHP:

$('#updateProduct').on('click', function() {
    try {
        ajaxRequest = new XMLHttpRequest();
    } catch (e) {
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("Your browser broke!");
                return false;
            }
        }   
    }
    ajaxRequest.open("POST", "../Controller/ProductController.php", true);
    ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    ajaxRequest.send("title=" + $("#title").val() + "&imgOne=" + $("#imgOne"));

    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            console.log(ajaxRequest);
        }
    }

});

在PHP中,我正在尝试这样做:

if (isset($_POST["edit"])) {
    $id = $_POST["edit"];
    $imgName = $_FILES["file"]["imgName"];
}

优素福


阅读 245

收藏
2020-07-26

共1个答案

小编典典

我在我的一个项目中做到了这一点,下面的代码对我有用。请根据需要对代码进行必要的修改。

我的表单按钮:

 <form name="upload_img" enctype="multipart/form-data" id="upload_img">
<input type="file" style="display:none" id="upload-image" name="upload-image"></input>
<button id="upload_image" type="button">Save</button>
</form>

我的JQuery / Ajax:

$('#upload_image').click(function()
{
    var form = new FormData(document.getElementById('upload_img'));
    //append files
    var file = document.getElementById('upload-image').files[0];
    if (file) {   
        form.append('upload-image', file);
    }
    $.ajax({
        type: "POST",
        url: "URL",
        data: form,             
        cache: false,
        contentType: false, //must, tell jQuery not to process the data
        processData: false,
        //data: $("#upload_img").serialize(),
        success: function(data)
        {
            if(data == 1)
                $('#img_msg').html("Image Uploaded Successfully");
            else
                $('#img_msg').html("Error While Image Uploading");
        }
    });
    //alert('names');


});
2020-07-26