To start things off, I've looked at a few similar problems on here but still can't resolve my issue here.
HTML:
<input type="file" name="filename" multiple="multiple" data-classIcon="icon-plus" data-buttonText="Upload Your File">
PHP:
$name = $_FILES['filename'];
$temp_name = $_FILES['filename']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = 'uploads/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'uploaded';
}
}
} else {
echo 'error: not uploaded';
}
JS:
$('#cc-submit').on('click', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "balanced/example.php",
data: $('#creditcardpost').serialize(),
success: function(data)
{
alert(data);
}
});
});
Error:
Undefined index: filename in /public_html/script.php on line xx (the two lines that collect the $_FILES variables.
"error: not uploaded"
You must use:
$name = $_FILES['filename']['name'];
I used print_r on $_FILES and found my files were coming through as "file-0". I'm not doing multi file uploads, so this works for me. And here is the solution. PHP:
$name = $_FILES['file-0']['name'];
$temp_name = $_FILES['file-0']['tmp_name'];
$location = '../uploads/';
if(move_uploaded_file($temp_name, $location.$name)){
}
print_r($name);
And the JS that sends it needed to be worked a bit:
var data = new FormData();
jQuery.each($('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
$.ajax({
url: 'balanced/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
$('#creditcardpost').append('<input type="hidden" value="' + data + '" name="filename" />');
}
});
I've got it working. Thanks for helping out guys.
Related
I am building a PHP application where a new user has to upload an avatar.
I managed to save the uploaded file path into my database,
but now I have to move the uploaded image from the temporary to the permanent directory, which is the folder 'avatars'.
I have searched through many answers on the same problem but haven't managed to find a working one. Since I am really new to PHP I'm gonna need some help for a working solution.
I have also tried copy() instead of move_uploaded_file with no luck.
HTML:
<div class="input-form">
<label for="avatar">Kies een profielfoto</label>
<input type="file" id="avatar-input" name="avatar" accept="image/*" onchange="loadFile(event)">
<img id="output" width="150" />
<input type="submit" id="submit-btn" name="vervolledig-submit" value="START">
</div>
PHP:
if(!empty($_POST)){
$fileSize = $_FILES["avatar"]["size"];
if($fileSize < 2000000){
$fileSizeOk = true;
}else{
throw new Exception("Je profielfoto heeft een grotere file size dan is toegelaten (max 2MB)");
$imgSizeOk = false;
}
$img = $_FILES["avatar"]["name"];
if($imgSizeOk == true){
move_uploaded_file($_FILES["avatar"]["tmp_name"], "avatars/$img");
}
}
EDIT: was asked to share my JS code:
a function that shows a preview of the uploaded picture:
let loadFile = function(event) {
let image = document.getElementById('output');
image.src = URL.createObjectURL(event.target.files[0]);
};
Suggested solution with AJAX
$('#submit-btn').on('click', function() {
var file_data = $('#avatar-input').prop('files')[0];
var form_data = new FormData();
form_data.append('avatar', file_data);
alert(form_data);
$.ajax({
url: 'profielVervolledigen.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
with the following php code:
if(!empty($_POST)){
if ( 0 < $_FILES['avatar']['error'] ) {
echo 'Error: ' . $_FILES['avatar']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['avatar']['tmp_name'], 'avatars/' . $_FILES['avatar']['name']);
}
}
the alert gives [object FormData]
Thanks for any help
First of all, I've just met with ajax and jquery and I must admit they seem pretty interesting. But I lost quite some time on figuring out why are my results in uploading img-s always the same.The idea is creating a page where I could import multiple images with some restrictions such as size and extension,but for some reason errors just aren't printing. It just prints alert("Image Uploaded") no matter what the result. This is the ajax part of my html:
<script>
$(document).ready(function(){
$('#uploadForm').on('submit', function(e){
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
processData:false,
success: function(data)
{
$("#gallery").html(data);
alert("Image Uploaded");
}
});
});
});
</script>
And this is the upload.php that I simply call in my html file:
<?php
//upload.php
$output = '';
if(is_array($_FILES))
{
foreach ($_FILES['files']['name'] as $name => $value)
{
$totalImageIndex = ($name+1);
$file_name = explode(".", $_FILES['files']['name'][$name]);
$file_size = $_FILES['files']['size'][$name];
$allowed_ext = array("png", "gif");
if(in_array($file_name[1], $allowed_ext))
{
if($totalImageIndex <= 5 ) {
// 2 MB is 2097152 bytes.
if($file_size < 2097152){
$new_name = $totalImageIndex . '.' . $file_name[1];
$sourcePath = $_FILES['files']['tmp_name'][$name];
$targetPath = "slike/".$new_name;
if(move_uploaded_file($sourcePath, $targetPath))
{
$output .= '<img src="'.$targetPath.'" width="150px" height="180px" />';
}
}
else { continue ; }
} else echo 'file is too big!';
} else echo 'wrong file format!';
}
echo $output;}
?>
Any idea or suggestion would be appriciated, thank u in advance!
In ajax on success you will get the data back that you echoed on your php file so either you get the image back or the error back you can simply alert(data); only and see what you getting in your ajax code you are alerting alert(image uploded) which will always be called as you are getting an error data also as success just remove that alert and do only alert(data) and you will see the error if any
I have form that allow me to submit text + number of files. the form submitted with AJAX.
Because it's a number of files my upload function give me error:
Warning: move_uploaded_file(images/usersFiles/14367317720-101.JPG) [function.move-uploaded-file]: failed to open stream: No such file or
directory in C:\Program Files
(x86)\wamp\www\new-site\func\global.func.php on line 134
line 134 is:
if (move_uploaded_file($files['file']['tmp_name'][$i], USER_FILES.$files['file']['name'][$i]))
files' var should be array (because I can load number of files).
How can I fix the error?
HTML:
<form class="form-horizontal" action='#' method="post" id="addCommentForm" enctype="multipart/form-data">
<textarea class="form-control" name="post[text]"></textarea>
<input type='file' name='file[]' class='multi form-control' maxlength='1' accept='gif|jpg|png|bmp' id="files"/>
<a class="btn btn-primary" id="submit">submit</a>
</form>
JS:
$(function() {
$("#submit").click(function() {
var file_data = $('#files').prop('files')[0];
var form_data = new FormData();
form_data.append('file[]', file_data);
var files_data = form_data;
var act = 'add';
form_data.append('act', act);
form_data.append('post[text]', $("#addCommentForm").find("textarea").val());
$.ajax({
type: "POST",
url: "ajax/addPost.php",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data)
{
$('#commentsBox').html(data);
$("#addCommentForm")[0].reset();
}
});
return false; // avoid to execute the actual submit of the form.
});
});
server:
function upload_files ($ownerID, $msg, $files, $type)
{
$dateLX = get_current_linuxTime();
///////// Upload files //////////////
if(!empty($files))
{
foreach($files['file']['name'] as $i => $fileName)
{
$fileSurffix = pathinfo ($_FILES['file']['name'][$i]);
$fileSurffix = $fileSurffix['extension'];
$files['file']['name'][$i] = str_replace(' ','',$files['file']['name'][$i]);
$files['file']['name'][$i] = $dateLX.$i."-".$ownerID.".".$fileSurffix;
$fileName = $files['file']['name'][$i];
if (move_uploaded_file($files['file']['tmp_name'][$i], USER_FILES.$files['file']['name'][$i]))
{
$uploadFilesQuery = "INSERT INTO `files` (ownerID, name, type)
VALUES('$ownerID', '$fileName', '$type')";
$res = mysql_query($uploadFilesQuery);
if (!$res)
$msg['error']['uploadFile'] = "error <br />".mysql_error();
}
elseif ($files['file']['error'][$i] != 4)
$msg['error']['uploadFile'] = "ERROR ";
}
}
return ($msg);
}
USER_FILES must be an absolute path like
"C:\Program Files (x86)\wamp\www\new-site\images\usersFiles\"
hello brothers i would like to ask you how can make a registration form with image upload(base64) usign php mysql ajax and this is a part of my code but it didn't work. i wish if you tell me the type of table row and give me the righ code to do this.
$("#dsubmit").click(function(){
var formData = new FormData(this);
demail=$("#demail").val();
dpassword=$("#dpassword").val();
dfirstname=$("#dfirstname").val();
dlastname=$("#dlastname").val();
dtel=$("#dtel").val();
dadr=$("#dadr").val();
dspeciality=$("#dspeciality").val();
dcodepost=$("#dcodepost").val();
$.ajax({
type: "POST",
url: "inc/regdoc.php",
data: formData,"&demail="+demail+"&dpassword="+dpassword+"&dfirstname="+dfirstname+"&dlastname="+dlastname+"&dtel="+dtel+"&dadr="+dadr+"&dspeciality="+dspeciality+"&dcodepost="+dcodepost,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(html){
if(html=='true') {
$("#dmsg_box_connexion").css("color","green");
$("#dmsg_box_connexion").html("Utilisateur Ajouté avec succés ! Redirection ...");
window.setTimeout(function(){window.location.href = "index.php";}, 5000);
} else {
$("#dmsg_box_connexion").html("S'il vous plaît remplir tous les champs");
}
},
beforeSend:function() {
if((demail == "")||(dfirstname == "")||(dlastname == "")||(dtel == "")||(dpassword == "")||(document.getElementById("dfile").value == "")||(dcodepost == "")||(dadr == "")) {
$("#dmsg_box_connexion").css("color","red");
$("#dmsg_box_connexion").html("Tous Les Champs Sont Obligatoires !");
return false;
}
$("#dmsg_box_connexion").css("clor", "#32b1d3");
$("#dmsg_box_connexion").html("Validation...");
}
});
return false;
});
});
and this is the php file :
session_start();
$email = addslashes(htmlentities($_POST["demail"]));
$password = addslashes(htmlentities($_POST["dpassword"]));
$firstname = addslashes(htmlentities($_POST["dfirstname"]));
$lastname = addslashes(htmlentities($_POST["dlastname"]));
$codepost = addslashes(htmlentities($_POST["dcodepost"]));
$adresse = addslashes(htmlentities($_POST["dadr"]));
$tel = addslashes(htmlentities($_POST["dtel"]));
$speciality = addslashes(htmlentities($_POST["dspeciality"]));
$get_content = file_get_contents($_FILES['dfile']['tmp_name']);
$escape = mysql_real_escape_string($get_content);
$sourcePath = $_FILES['dfile']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "uploads/".$_FILES['dfile']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
$pass = sha1($password);
include ('pgs/config.php');
$insert = $bdd->query("INSERT INTO tbl_docs VALUES ('','$firstname','$lastname','$tel','$adresse','$speciality','$email','$pass','$escape','1','$codepost')");
if($insert == 1) {
echo 'true';
} else {
echo 'false';
}
and this is th form header:
<form id="d" method="post" action="#inc/regdoc.php" enctype="multipart/form-data">
Check the working example i have implemented in my project how to submit a form with image and some data fields.
$(document).on('submit', '#catcategory-form', function(event) {
event.preventDefault();
$.ajax({
url: "product.php",
method: 'POST',
data: new FormData(this),
dataType: 'json',
contentType: false,
processData: false,
success: function(infodata) {
if(infodata=='true'){
//do the stuff whatever you want
}
});
});
The another option you can do with image upload is convert base64. What you have to do is convert you form image in base 64 and send it on onChange event to the php and upload it in a file and keep the unique name in your database
//Call this function after getting base64 by post
$imageBase64=$_POST['image_converted_base64'];//get base64 of image from client end
$unique_name =uploadSingleImage($imageBase64);//function call
//function to upload image and get an unique name to store in db
function uploadSingleImage($base64) {
$uniname = uniqid() . date("Y-m-d-H-i-s") . ".jpg";
$new_image_url = "../../image/" . $uniname;
$base64 = 'data:image/jpeg;base64,' . $base64;
$base64 = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $base64));
file_put_contents($new_image_url, $base64);
return $uniname;
}
$sql = "INSERT INTO `table1`(image_name) VALUES('$unique_name')";
$conn->query($sql);
So the html code i have:
<form id="loginIMGForm">
<input type="file" name="file" id="loginIMG" />
<br />
<input type="submit" name="submit" value="Submit" id="submitloginIMG" />
</form>
<div id="loginIMGStatus">Select an image and upload.</div>
and then PHP code i have:
<?php
$imageinfo = getimagesize($_FILES['loginIMGForm']['tmp_name']);
if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg') {
echo "Sorry, we only accept GIF and JPEG images\n";
exit;
}
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['loginIMGForm']['name']);
if (move_uploaded_file($_FILES['loginIMGForm']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "File uploading failed.\n";
}
?>
and jquery is:
$('#loginIMGForm').submit(function() {
// 'this' refers to the current submitted form
var str = $(this).serialize();
alert(str);
$.ajax({
type: "POST",
url: "modules/upload.php",
data: str,
success: function(msg){
$("#loginIMGStatus").ajaxComplete(function(event, request, settings){
if(msg == 'OK'){ result = 'Login Image is updated'; }
else{ result = msg; }
$(this).html(result);
});
}
});
return false;
});
I did debuging using alert, the data is empty. What did I do wrong.
Thanks.
Why are you calling ajaxComplete?
Just do this instead:
$.ajax({
type: "POST",
url: "modules/upload.php",
data: str,
success: function(msg){
var result;
if(msg == 'OK'){ result = 'Login Image is updated'; }
else{ result = msg; }
$(this).html(result);
});
}
});
Also, when you say the data is empty, do you mean when you call alert or the html component?
Edit You can't use serialize on a file. It isn't supported and doesn't really make sense. See this page. Also, although it wasn't an issue yet, I do suspect you're going to have problems with calling ajaxComplete. The success parameter already handles calling your function when the ajax request completes. I'm not really sure what will happen with your code.