Home > Mobile >  How to upload file using axios to database?
How to upload file using axios to database?

Time:10-28

I don't know how to send/upload file to database using axios while not using vue and react.

<script>
                        var submit1 = document.getElementById("submit");
                        submit1.addEventListener("click", function(e){
                            e.preventDefault();
                            var email1 = document.getElementById("email").value;
                            var f2 = document.getElementById("file").value;
                            var url = "apply2.php";
                            var data = {usEmail:email1,usF2:f2};
                            axios.post(url,data)

                            .then(function(res){
                                alert(res.data)
                                
                            })
                            .catch(function(error){
                                alert("erre");
                            })
                        });
                    </script>

And this is apply2.php where



$_POST = json_decode(file_get_contents('php://input'),true);

$e = mysqli_real_escape_string($conn, $_POST['usEmail']);

$filet1 = rand(1000, 10000) . "-" . $_FILES["usF2"]["name"];
    $tname1 = $_FILES["usF2"]["tmp_name"];
    $uploads_dir1 = '../files';
    move_uploaded_file($tname1, $uploads_dir1 . '/' . $filet1);



$sql = "INSERT into applyey(email,file) 
    VALUES('$e','$filet1')";


I don't know why it won't work with file but works with email.

CodePudding user response:

You need to add data to formdata object and content-type as multipart

var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("usF2", imagefile.files[0]);
var email1 = document.getElementById("email").value;
formData.append("usEmail", email1);
var url = "apply2.php";
axios.post('url', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})
  • Related