简体   繁体   中英

upload image from multiple form with ajax and php

in PHP page with multiple form tag to register user information. using ajax to collect data and post to register PHP page now i want to upload image to server folder but i failed.

my html code:

<label for="upimage" class="btn btn-sm btn-primary mb-75 mr-75">Upload Image</label>
<input type="file" id="upimage" hidden accept="image/*" name="image"/>

Javascript Code:

let data1 = document.getElementById('data1').value,
    data2 = document.getElementById('data1').value,
    data3 = document.getElementById('data1').value,
    upimage = document.getElementById('upimage').value;
$.ajax({
    url:"././newregister.php",
    method:"POST",
    data:{action:'newregister', data1:data1, data2:data2,
        data3:data3, upimage:upimage},
    success:function(data){
        alert(data);
    }
});

newregister php code:

$uploads_dir = './uploads';
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
    $tmp_name = $_FILES["file"]["tmp_name"];
    $name = $_FILES["file"]["name"];
    move_uploaded_file($tmp_name, "$uploads_dir/$name");
    echo "Sucsess"; 
}
else
{
    echo "Error" . $_FILES["file"]["error"] ; 
}

ERR: Undefined index: file in.... on line....

Given by POST method uploads

Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.

Your current solution lacks enctype, that's why your file is not getting uploaded to the server and therefore isn't in the superglobal variable $_FILES.


As ferikeem already said. Wrap your data in a FormData Object and send it that way. See: https://stackoverflow.com/a/5976031/10887013

JavaScript

let fd = new FormData();
fd.append("you_file_key_here", $("#upimage")[0].files[0]);
fd.append("data1", $("#data1")[0].value);
fd.append("data2", $("#data2")[0].value);
fd.append("data3", $("#data3")[0].value);

$.ajax({
    url: "././newregister.php",
    method: "POST",
    data: fd,
    processData: false,
    contentType: false,
    success: function(data){
        alert(data);
    }
});

$_FILES["file"] , here is your problem.

In $_FILES array key "file" doesn't exists. As I see you need to change $_FILES["file"] with $_FILES["upimage"] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM