简体   繁体   中英

Doubts in uploading image into file database using ajax

Focus on the questions, please

I have the following HTML

 <form enctype="multipart/form-data" onsubmit="uploadProfilePicture();" method="post" name="prof_picture">
 <input id="upload_profile_picture" style="display:none;"name="image" accept="image/jpeg" type="file">
 <input id="upload_profile_picture2" value="Submit" type="submit" style="display:none;">
 <a id="change_profile_picture" class="profile_option" onclick="$('#upload_profile_picture').click();">Mudar foto de perfil</a>

PHP (profileFunctions.php)

if(isset($_POST['prof_picture'])){
    alert("test");
}

JS

function uploadProfilePicture(){

    $.ajax({
            type:'POST',
            url: "profile/profileFunctions.php",
            data:$(this).serialize(),
            cache:false,
            success:function(data){
                console.log("success");
                console.log(data);
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });

}

I have used ajax before but the thing is I'm actually really in doubt because of this file being an image:

1º What exactly should be in "data:" within the ajax request? And what should I do to parse the file correctly?

2º In PHP image validation how can I retrieve the extension of the file AND how exactly should I do the isset($_POST)?

3º If I am to propose the image to the user instantly if ajax.success should cache be set to true? How does cache behave on this situation?

XHR technology does not permit to upload the images.

You have to find a workaround, something like using an iframe.

Please use iframe instead of ajax.

<form target="my_iframe_name" action="my_script_can_receive_file.php" ....>
...
</form>
<iframe name="my_iframe_name"  onload="javascript:alert('uploaded')" style="width:1px;height:1px;position:absoulte;left:-99999px;top:-99999px" src="javascript:void(0)"></iframe>

However, if you want check the status of your upload, you may need more work on both [my_script_can_receive_file.php] and [js] to talk the status to the main frame.

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