I've just written a script to upload images and i've checked it for a long but I can't find where is the error. The entire code do what it's supposed to do but the move_uploaded_file(); function doesn't. Here is my code:
HTML:
<form method="post" id="img-form" enctype="multipart/form-data">
Subir imagen: <input type="file" name="file">
</form>
<div id="respuesta"></div>
JS:
$(function(){
$("input[name='file']").on("change", function(){
var formData = new FormData($("#img-form")[0]);
$.ajax({
url: "ajax/uploadimage.php",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(data)
{
$("#respuesta").html(data);
}
});
});
});
PHP:
<?php
require '../init.php';
if (isset($_FILES["file"]))
{
$file = $_FILES["file"];
$nombre = $file["name"];
$type = $file["type"];
$ruta_provisional = $file["tmp_name"];
$size = $file["size"];
$gethandw = getimagesize($ruta_provisional);
$width = $gethandw[0];
$height = $gethandw[1];
$path = "img/users/";
if ($type != 'image/jpg' && $type != 'image/jpeg' && $type != 'image/png' && $type != 'image/gif')
{
echo "Error, el archivo no es una imagen";
}
else if ($size > 1024*1024)
{
echo "Error, el tamaño máximo permitido es un 1MB";
}
else if ($width > 400 || $height > 400)
{
echo "Error la anchura y la altura maxima permitida es 500px";
}
else if($width < 60 || $height < 60)
{
echo "Error la anchura y la altura mínima permitida es 60px";
}
else
{
$src = $path.$nombre;
move_uploaded_file($ruta_provisional, $src);
echo "<img src='$src'>";
}
}
The answer (data) outputs everything correct but the image is not uploading anywhere, I'm using xampp for testing
Your PHP code seems ok. I found some issues with your implementation of FormData. Please try the below code
JS
$(function(){
$("input[name='file']").on("change", function() {
var formData = new FormData();
formData.append('file', $(this)[0].files[0]);
$.ajax({
url: "ajax/uploadimage.php",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(data) {
$("#respuesta").html(data);
}
});
});
});
Please let me know if you are still facing difficulties. Hope this helps.Thanks
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.