简体   繁体   中英

Upload a file Using PHP and JavaScript

I selected a image using:

<input type="file" id="pimg" name="pimg" accept='image/*'/>  

My javascript code:

p_img =document.getElementById("pimg").value;  
param= 'pn='+p_img;  
xmlhttp.open("GET","add_prod.php?"+param,false);  
xmlhttp.send();  

My php code:

p_img=$_GET['img'];
$con = mysqli_connect('localhost', 'admin', 'admin', 'products');
$sql="INSERT INTO prod (img) VALUES ('$p_img')";
if (!mysqli_query($con,$sql))
{
    die('Error: ' . mysqli_error($con));
}  

This will store only the name of the file. But i want to copy the file from pc to directory. Its necessary to use Javascript as I'm using complete add product to pass values using AJAX

Create index.html file

<!DOCTYPE html>
<html>
<body>
    <form action="upload_file.php" method="post" enctype="multipart/form-data">
        <label for="file">Filename:</label>
        <input type="file" name="file" id="file"><br>
        <input type="submit" name="submit" value="Submit">
    </form>
</body>
</html>

Create Php file upload_file.php

<?php

if ($_FILES["file"]["error"] > 0) {
    echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
}

?>

Use POST (form) to send data to the php file.

With $_FILES["pimg"]["tmp_name"] you can move the uploaded file (with the php function move_uploaded_file to you webserver.

Link to PHP Function http://php.net/manual/de/function.move-uploaded-file.php

You can upload the file without page refresh using simple JavaScript and PHP. Using JavaScript, the file would be passed to the PHP file and using move_uploaded_file() function file would be uploaded to the server.

The live demo and source code would found from here - Upload file using JavaScript and PHP

xmlhttp.open("GET","add_prod.php?"+param,false);  

我认为 open 方法的参数必须包含 true。

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