-1

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Oct 27 '22 at 09:34

1 Answers1

0

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'
    }
})
Shibon
  • 1,552
  • 2
  • 9
  • 20
  • THANKS, it work but the email didnt get inserted into database. when I removed $_POST = json_decode(file_get_contents('php://input'),true); it work what does this do? – Dolms Pansag Oct 27 '22 at 10:23