I'm new to file uploads, I'm not quite sure what is wrong. Every time I try to upload a file, the server responds saying "File not Uploaded" since $_FILE["file1"] is not set. It is the same with $_FILES["file1"]["tmp_name"] for getimagesize(). I have a gut feeling there is a problem with my AJAX request.
PHP INI FILE has file_uploads = On
My file is within the max file upload size boundaries
I was using a .jpg file for testing.
PHP FILE UPLOAD CODE:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file1"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(!isset($_FILES["file1"])){ //File is always not set ?
echo "File not Uploaded";
die();
}
$check = getimagesize($_FILES["file1"]["tmp_name"]);
if ($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.".$_FILES["file1"]["error"];
$uploadOk = 0;
die();
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
die();
}
// Check file size
if ($_FILES["file1"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
die();
}
// Allow certain file formats
if ($imageFileType !== "jpg" && $imageFileType !== "png" && $imageFileType !== "jpeg" && $imageFileType !== "gif") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
die();
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
die();
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file)) {
echo "The file " . basename($_FILES["file1"]["name"]) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
AJAX UPLOAD SCRIPT:
function _(str) {
return document.getElementById(str);
}
function uploadFile() {
var formData = new FormData($('form')[0]);
alert(formData);
$.ajax({
url: 'file.php', //Server script to process data
type: 'POST',
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
success: function (data) {
_("filename").innerHTML = data;
},
});
function progressHandlingFunction(e) {
if (e.lengthComputable) {
$('progress').attr({value: e.loaded / e.total, max: e.total});
}
}
}
HTML DOC:
<form action='/' method='post' enctype="multipart/form-data">
<input type="button" onclick="document.getElementById('file1').click();
return false;" value="Upload File" class="btn btn-primary">
<span id="filename" class="label label-success"></span>
<input type="file" id="file1" name="file1" style="visibility: hidden" onchange="filenameprint()">
<input type="button" onclick="uploadFile()" value="Upload File">
<script>
function filenameprint() {
var file1 = document.getElementById('file1').value;
if (!empty(file1)) {
document.getElementById('filename').innerHTML = file1;
} else {
document.getElementById('filename').innerHTML = "No File Chosen"
}
}
</script>
<progress value="0" max="100"></progress>
</form>
I think you are sending the wrong formData. You should just send the file.
var fileInput = $('#file1');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
Related
Edit: Also I want to add, I get no errors whatsoever either in js, or PHP.
Technically, am using a form where I want the seller to fill up the necessary stuff of a product, also including the Image of the product to show in the Shopping area. I hate the default input type file of html5, and I have a hard time hiding it, so I came across with dropzone. Now dropzone kinda works on the client side, but doesn't seem to be working on the Server side. No file gets uploaded on the redirect I want it to be sent.
This is kind of a new thing to me, so I'm lost on what to do.
this is the html code
<form enctype='multipart/form-data' action='upload.php' method='POST'>
<div class='form-group'>
<input class='form-control' type='text' placeholder='Title' id='titleInput' name='titleInput'>
</div>
<div class='form-group'>
<input class='form-control' type='number' placeholder='Price' id='priceInput' name='priceInput'>
</div>
<div class='dropzone' id='myDropzone'>
</div>
<button id='submit-all' type='submit' name='Post'>Submit<\button>
</form>
the javascript code
Dropzone.options.myDropzone= {
url: 'upload.php',
paramName: "file",
autoProcessQueue: false,
uploadMultiple: false,
//parallelUploads: 5,
//maxFiles: 5,
maxFilesize: 1,
acceptedFiles: 'image/*',
addRemoveLinks: true,
init: function() {
dzClosure = this; // Makes sure that 'this' is understood inside the functions below.
// for Dropzone to process the queue (instead of default form behavior):
document.getElementById("submit-all").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
//e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
//send all the form data along with the files:
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("titleInput", jQuery("#titleInput").val());
formData.append("priceInput", jQuery("#priceInput").val());
});
}
}
And the upload.php code
<?php
if(isset($_POST['Post'])){
if(isset($_FILES['file']['name'])){
$imageName = $_FILES['file']['name'];
$imageNameTemp = $_FILES['file']['tmp_name'];
echo $imageName;
}
else{
$imageName = "";
echo "null";
}
$errorMessage = "";
if($imageName != "") {
$targetDir = "assets/images/productImages/";
$imageName = $targetDir . uniqid() . basename($imageName);
$imageFileType = pathinfo($imageName, PATHINFO_EXTENSION);
if($_FILES['file']['size'] > 5000000) {
$errorMessage = "Sorry your file is too big!";
$uploadOk = 0;
}
if(strtolower($imageFileType) != "jpeg" && strtolower($imageFileType) != "png" && strtolower($imageFileType) != "jpg") {
$errorMessage = "Sorry, only jpeg, jpg and png files are allowed";
$uploadOk = 0;
}
if(strtolower($imageFileType) == "jpeg" || "jpg"){
$src = imagecreatefromjpeg($imageNameTemp);
}
if(strtolower($imageFileType) == "png"){
$src = imagecreatefrompng($imageNameTemp);
}
if($uploadOk == 1) {
list($width_min, $height_min) = getimagesize($imageNameTemp);
if($width_min > 1920){
$newwidth_min = 1920;
$newheight_min = ($height_min / $width_min) * $newwidth_min;
}
else if($height_min > 1920){
$newheight_min = 1920;
$newwidth_min = ($height_min / $width_min) * $newheight_min;
}
else{
$newheight_min = $height_min;
$newwidth_min = $width_min;
}
$tmp_min = imagecreatetruecolor($newwidth_min, $newheight_min);
imagecopyresampled($tmp_min, $src, 0, 0, 0, 0, $newwidth_min, $newheight_min, $width_min, $height_min);
imagejpeg($tmp_min, $imageName);
$uploadOk = 1;
}
else {
//image did not upload
$uploadOk = 0;
}
}
}
?>
So, when it redirects to upload.php, it echoes null because that what i wrote, if no file is sent.
Please help
I am trying to create a form where when the user chooses a file, the file chosen will automatically upload to the database by going to the action in form. I used the onchange function and it just sends me to my php file in which that file contains my uploading system. What i think my problem is about my $_POST['asdasd'], but i cant really think of any other solutions to this.
Here is my form:
<form action="includes/profile_picture_inc.php" method="POST" enctype="multipart/form-data" id="form">
<input type="file" name="file" id="upload" onchange="document.getElementById('form').submit();">
</form>
The PHP File:
if (isset($_POST['submit'])) {
$target_dir = "../users/".$_SESSION['u_id']."/image/";
$str = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
$rand = substr(str_shuffle($str), 0, 10);
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = $rand . '.' . end($temp);
$target_file = $target_dir . $newfilename;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ". <br/>";
$uploadOk = 1;
} else {
echo "File is not an image. <br/>";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists. <br/>";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 5000000) {
echo "Sorry, your file is too large. <br/>";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed. <br/>";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded. <br/>";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
require 'database_inc.php';
$sql = "UPDATE `users` SET `user_profile` = '$newfilename' WHERE 1";
if (mysqli_query($conn,$sql)) {
$_SESSION['profile_picture'] = $newfilename;
header("Location: ../profile.php");
} else {
echo "The query has not been updated. <br/>";
}
} else {
echo "Sorry, there was an error uploading your file. <br/>";
}
}
}
It is not saving because in the php file you have the line
if (isset($_POST['submit'])) {
add in the form a hidden field
<form action="includes/profile_picture_inc.php" method="POST" enctype="multipart/form-data" id="form">
<input type="file" name="file" id="upload" onchange="document.getElementById('form').submit();">
<input type="hidden" name="submited" value="1" />
</form>
And in php change the line
if (isset($_POST['submit'])) {
to
if (isset($_POST['submited'])) {
That should do it
Instead of doing the $_POST['submit'] validation, try to check if the request is a $_POST.
To do that you can use something like
if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') { … }
or
if ($_SERVER['REQUEST_METHOD'] === 'POST') {…}
i recommend you to use the first one.
PHP doc: http://php.net/manual/pt_BR/function.filter-input.php
I have a blob object and some data need to be post to fileHandler.php
so I pack them into a FormData:
console.log("start saving");
var url1 = URL.createObjectURL(blob);
var url2 = "data:application/octet-stream," + encodeURIComponent(JSON.stringify(dataPack));
console.log(url1);
console.log(url2);
fd.append('realName', dataPack.name);
fd.append("ans", JSON.stringify(dataPack.ans));
fd.append("log", JSON.stringify(dataPack.log));
fd.append("part", dataPack.part);
fd.append('fileToUpload', blob);
window.postData = fd;
and upload them via ajax:
$.ajax({
type: 'POST',
url: '../php/fileHandler.php',
data: postData,
processData: false,
contentType: false,
success: function() {
uploadSuccess();
},
error: function() {
uploadFail();
},
progress: function(e) {
console.log(e);
//make sure we can compute the length
if(e.lengthComputable) {
//calculate the percentage loaded
var pct = parseInt((e.loaded / e.total) * 100);
//log percentage loaded
$('#uploadProgress').width(pct+"%").text(pct+"%");
console.log(pct);
}
//this usually happens when Content-Length isn't set
else {
console.warn('Content Length not reported!');
}
}
}).done(function(data) {
console.log(data);
if(data ==="ok") {
uploadSuccess();
}
else {
uploadFail();
}
});
php file handler:
<?php
$target_dir = "uploads/";
$realName = trim($_POST['realName']);
$part = $_POST['part'];
$ans = json_decode($_POST['ans']);
$log = json_decode($_POST['log']);
$fileNameNoEx = $target_dir . $realName . "-" . $part ."-". time();
$target_file = $fileNameNoEx . ".mp3";
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
//save files
$f = fopen($fileNameNoEx.".txt", "w");
fwrite($f, "Answer log:\n");
foreach ($ans as $page => $val) {
fwrite($f, "$page : $val\n");
}
fwrite($f, "\nPage switching event log:\n");
foreach ($log as $l) {
fwrite($f, "{$l->time}s ---> {$l->page}\n");
}
fclose($f);
echo "ok";
} else {
var_dump($ans);
var_dump($log);
var_dump($_POST);
var_dump($_FILES);
var_dump($target_file);
echo "asdsad";
echo "Sorry, there was an error uploading your file.";
}
}
then strange things happen, sometimes uploading failed, and I when I try to upload again(in console, with the same data), browser keep logging:
NULL
NULL
array(0) {
}
array(0) {
}
string(24) "uploads/--1500100885.mp3"
asdsadSorry, there was an error uploading your file.
it seems that postData is empty? But when I check the postData in browser console:
> postData.get("fileToUpload")
File {name: "blob", lastModified: 1500101804839, lastModifiedDate: Sat Jul 15 2017 14:56:44 GMT+0800 (China Standard Time), webkitRelativePath: "", size: 12597888…}
> postData.get("realName")
"jjj"
why???? how can $_FILES[] and $_POST[] be emtpy?
This problem happens often when the file is very large.
PHP has a maximum post size, try to increase it: Increasing the maximum post size
If PHP didn't have this limit I could send an infinitely large POST to your web server until either it runs out of disk or RAM.
I wrote the script for uploading image in folder say (upload) in my case.
It's working perfectly !
I just want to get response message in json.
I don't know how to use json in scrip and where.
Thanks !
script.js
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
// Function to preview image after validation
$(function() {
$("#file").change(function() {
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#previewing').attr('src','noimage.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$("#file").css("color","green");
$('#image_preview').css("display", "block");
$('#previewing').attr('src', e.target.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
};
});
ajax_php_file.php
<?php
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
firstly pass a property in ajax
dataType: "JSON"
next you have to build and array of all the data that your out putting in stead of echo for eg
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
change to
$respons['msg']="<span id='invalid'>***Invalid file Size or Type***<span>";
then use
echo json_encode($respons);
this will pass a json object your client side
once there you can console output your data to see how to access the nested objects
i'm having trouble uploading image with other input text form and send to ajax_php_file.php. But only image is uploaded, my input text is all empty. Would appreciate if anyone can assist here. Thanks alot.
<div id="imagebox">
<div class="image_preview">
<div class="wrap">
<img id="previewing" />
</div>
<!-- loader.gif -->
</div><!--wrap-->
<!-- simple file uploading form -->
<form id="uploadimage" method="post" enctype="multipart/form-data">
<input id="file" type="file" name="file" /><br>
<div id="imageformats">
Valid formats: jpeg, gif, png, Max upload: 1mb
</div> <br>
Name:
<input id="name" type="text"/>
<input id="cat" type="hidden" value="company"/>
Description
<textarea id="description" rows="7" cols="42" ></textarea>
Keywords: <input id="keyword" type="text" placeholder="3 Maximum Keywords"/>
<input type="submit" value="Upload" class="pre" style="float:left;"/>
</form>
</div>
<div id="message">
</div>
script.js
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
var name = document.getElementById("name").value;
var desc = document.getElementById("description").value;
var key = document.getElementById("keyword").value;
var cat = document.getElementById("cat").value;
var myData = 'content_ca='+ cat + '&content_desc='+desc+ '&content_key='+key+ '&content_name='+name;
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this,myData), // Data sent to server, a set of key/value pairs representing form fields and values
//data:myData,
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
// Function to preview image
$(function() {
$("#file").change(function() {
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#previewing').attr('src','noimage.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$("#file").css("color","green");
$('#image_preview').css("display", "block");
$('#previewing').attr('src', e.target.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
};
});
ajax_php_file.php
<?php
session_start();
$user_signup = $_SESSION['user_signup'];
if(isset($_FILES["file"]["type"]))
{
$name = filter_var($_POST["content_name"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$ca = filter_var($_POST["content_ca"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$desc = filter_var($_POST["content_desc"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$key = filter_var($_POST["content_key"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
$imagedata = addslashes(file_get_contents($_FILES['file']['tmp_name']));
$imagename= ($_FILES['file']['name']);
$imagetype =($_FILES['file']['type']);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 1000000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
mysql_query("INSERT INTO upload(name,picname,image,type,email,cat,description,keyword) VALUES('".$name."','".$imagename."','".$imagedata."','".$imagetype."','".$user_signup."','".$ca."','".$desc."','".$key."')");
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>
the format of the formData maybe incorrect. Change it like the following:
var myData = {'content_ca':cat,
'content_desc':desc
}
i think you are using jquery
So you can use
data:$("#uploadimage").serialize(),