I am trying to create a facebook like status update where I want a user to be able to upload images exactly like facebook does. I have the following codes which allows a user to upload and preview images and remove them by clicking on a 'X' button.
HTML Form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="newstatus" runat="server" enctype="multipart/form-data">
<textarea name="status" class="textarea newstatuscontent" placeholder="What are you thinking?"></textarea>
<input type="file" name="files[]" multiple="multiple" id="file-5" class="inputfile inputfile-4">
<div id="imgs"></div> // images preview and container
<input type="submit" name="post" value="Post" class="post-btn" id="submit" />
</form>
Ajax code to insert data to the database:
$(function() {
$("#submit").click(function() {
$(this).val("Please wait...");
var textcontent = $(".newstatuscontent").val();
/*if(media == ''){*/
if(textcontent == ''){
$('.cap_status').html("Status cannot be empty. Please write something.").addClass('cap_status_error').fadeIn(500).delay(3000).fadeOut(500);
$("#submit").val("Post");
}else{
/*}else{*/
$.ajax({
type: "POST",
url: "post-status.php",
data: {content:textcontent},
cache: true,
success: function(html){
$("#shownewstatus").after(html);
$(".newstatuscontent").val('');
$("#submit").val("Post");
}
});
}
//}
return false;
});
});
jQuery for Images preview:
function del(index) {
$('div.img_'+index).remove();
updateFiles();
}
function updateFiles() {
var fileIndexes = $('#imgs > div').map(function() {
return $(this).data('index');
}).get().join(",");
$('#files_selected').val(fileIndexes);
}
$(document).ready(function() {
$("#file-5").on('change', function() {
var fileList = this.files;
$('#imgs').empty();
if($('#imgs') != null){
$('.post-btn').css("margin-top","5px");
}
//$('#dimg').empty();
for (var i = 0; i < fileList.length; i++) {
var t = window.URL || window.webkitURL;
var objectUrl = t.createObjectURL(fileList[i]);
$('#imgs').append('<div data-index="' + i + '" class="img_' + i + '"><span class="img_' + i + '" onclick="del(' + i + ')" style="cursor:pointer; margin-right: 3px;"><b>x</b></span><img class="img_' + i + '" src="' + objectUrl + '" width="160" height="160" style="margin-right: 3px;"></div>');
j = i + 1;
if (j % 3 == 0) {
$('#imgs').append('<br>');
}
}
updateFiles();
});
});
post-status.php:
<?php
session_start();
include('config/db.php');
$time = date('Y-m-d H:i:s');
$curr_date = date('Y-m-d');
$yest = date("Y-m-d", strtotime("-1 day"));
$status = (!empty($_POST['content']))?nl2br(trim($_POST['content'])):null;
$status_fix = str_replace(array("\r", "\n"), '', $status);
$post = "INSERT INTO status(sts_status, sts_mem, sts_time)VALUES(:status, :mem, :time)";
$posq = $pdo->prepare($post);
$posq->bindValue(':status', $status_fix);
$posq->bindValue(':mem', $user_id);
$posq->bindValue(':time', $time);
$posq->execute();
$lastid = $pdo->lastInsertId();
?>
I want to combine the Image preview code with the ajax code above so that I can insert the data to the database. Now what I want?
Say for example I first selected 4 images like a.jpg, b.jpg, c.jpg, d.jpg. Then I got their preview. Then say I thought to remove b.jpg so I removed it. Now I have only the three images in preview a.jpg, c.jpg, d.jpg. Now finally, I want to rename these three files when I click on post to some random names and upload these images to the upload folder and insert their renamed names to the database.
NOTE: I want to insert and upload only those images that are in the preview div <div id="imgs"> and not from <input type="file">.
Please help me guys. I made it as much clear as possible. What I have already coded is already given above. Struggling with this problem from quite a few days. Please help me tackle this problem.
Related
Basically, I want my user to fill some input form and upload a lot image file in one form. Here is the little piece of the code.
<?php echo form_open_multipart('', array('id' => 'upload', 'enctype' => "multipart/form-data")); ?>
<div class="form-group col-sm-3 col-md-4">
<label for="last5">Last 5 Test</label>
<input type="text" name="last5" id="last5" class="form-control" />
</div>
<div class="form-group col-sm-3 col-md-4">
<label for="cert5">Certified By</label>
<input type="text" name="cert5" id="cert5" class="form-control" />
</div>
<div class="form-group col-sm-3 col-md-2">
<label for="driver">Driver</label>
<input type="text" name="driver" id="driver" class="form-control" />
</div>
/*This is for upload file*/
<div class="form-group col-sm-12">
<label for="file">Upload Foto</label>
<input name="file[]" id="file" type="file" multiple >
</div>
<div class="form-group col-sm-6 col-md-6 ">
<button type="submit" class="btn btn-primary btn-block">Update & Submit</button>
</div>
<div class="form-group col-sm-6 col-md-6">
<button type="reset" class="btn btn-default btn-block">Reset</button>
</div>
<?php echo form_close(); ?>
I use php codeigniter on side server. Now, to submit those data, I use AJAX twice, first, I want make sure the common input is success then upload those file on next.
So, I declare those file input :
$("#file").fileinput({
dropZoneEnabled : false,
showUpload : false,
uploadUrl: "http://localhost/depo/", // Please, triggered upload
uploadAsync: false,
maxFileCount: 10
});
And here is the AJAX :
$(document).on('submit', '#upload', function (e) {
e.preventDefault();
$('#no_surat').prop("disabled", false);
var form = $('#upload');
var inputFile = $('input#file');
var filesToUpload = inputFile[0].files;
// make sure there is file(s) to upload
if (filesToUpload.length > 0) {
// provide the form data that would be sent to sever through ajax
var formData = new FormData();
for (var i = 0; i < filesToUpload.length; i++) {
var file = filesToUpload[i];
formData.append("file[]", file, file.name);
}
$.ajax({ //Upload common input
url: "<?php echo base_url('surveyor/c_surveyor_inspection/update_by_inspection_surveyor_2'); ?>",
type: "POST",
data: form.serialize(),
dataType: 'json',
success: function (response) {
if (response.Status === 1) {
$.ajax({ //Then upload the foto
url: "<?php echo base_url('surveyor/c_surveyor/add_file_image/'); ?>/" + response.Nama_file + '/' + response.No_surat,
type: 'post',
data: formData,
processData: false,
contentType: false,
success: function (obj) {
$('#no_surat').prop("disabled", true);
console.log("The photos is successfully upload");
}, fail: function () {
console.log('Error');
}
});
}
}
});
} else {
$('#file').after('<div class="callout callout-danger lead" id="div_error"><p id="pesan_error"></p></div>');
$('#div_error').fadeIn("fast");
$('#pesan_error').html("Harap sertakan foto...");
$('#div_error').fadeOut(7000);
}
return false;
});
This is the code to handling image upload:
public function add_file_image() {
$last = $this->uri->total_segments();
$id = $this->uri->segment($last);
echo urldecode($this->uri->segment($last));
$pathToUpload = "D:\Foto\ " . $this->uri->segment(4, 0) . '-' . $this->uri->segment(5, 0);
if (!is_dir($pathToUpload)) {
mkdir($pathToUpload, 0755, true);
mkdir($pathToUpload . '\thumbs', 0755, true);
}
$dir_exist = true; // flag for checking the directory exist or not
if (!is_dir($pathToUpload)) {
mkdir($pathToUpload, 0755, true);
mkdir($pathToUpload . '\thumbs', 0755, true);
$dir_exist = false; // dir not exist
}
if (!empty($_FILES)) {
$config['upload_path'] = $pathToUpload;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = $id;
$config['overwrite'] = FALSE;
//$config['encrypt_name'] = TRUE;
$this->load->library('upload');
$files = $_FILES;
$number_of_files = count($_FILES['file']['name']);
$errors = 0;
$upload_array = array();
// codeigniter upload just support one fileto upload. so we need a litte trick
for ($i = 0; $i < $number_of_files; $i++) {
$_FILES['file']['name'] = $files['file']['name'][$i];
$_FILES['file']['type'] = $files['file']['type'][$i];
$_FILES['file']['tmp_name'] = $files['file']['tmp_name'][$i];
$_FILES['file']['error'] = $files['file']['error'][$i];
$_FILES['file']['size'] = $files['file']['size'][$i];
// we have to initialize before upload
$config['file_name'] = $this->uri->segment(4, 0) . '-' . $this->uri->segment(5, 0) . '-' . $i;
// UPLOAD EKSEKUSI
$this->upload->initialize($config);
if (!$this->upload->do_upload("file")) {
$errors++;
echo $this->upload->display_errors();
} else {
$upload_data = $this->upload->data();
print_r($upload_data);
$new_upload = array(
"NO_INSPECTION" => $id,
"file_name" => $upload_data['file_name'],
"file_orig_name" => $upload_data['orig_name'],
"file_path" => $upload_data['full_path']
);
$this->load->library('image_lib');
$resize_conf = array(
'source_image' => $upload_data['full_path'],
'new_image' => $upload_data['file_path'] . '\thumbs\thumb_' . $upload_data['file_name'],
'width' => 200,
'height' => 200
);
//use first config
$this->image_lib->initialize($resize_conf);
//run resize
if (!$this->image_lib->resize()) {
echo "Failed." . $this->image_lib->display_errors();
}
//clear
$this->image_lib->clear();
//initialize second config
$this->image_lib->initialize($resize_conf);
//run resize
if (!$this->image_lib->resize()) {
echo "Failed." . $this->image_lib->display_errors();
}
//clear
$this->image_lib->clear();
//push all informatin to array for insert batch
array_push($upload_array, $new_upload);
}
}
//Insert batch codeingter
$this->m_surveyor->save_files_info($upload_array);
if ($errors > 0) {
echo $errors . "File(s) cannot be uploaded";
}
} elseif ($this->input->post('file_to_remove')) {
$file_to_remove = $this->input->post('file_to_remove');
unlink("./assets/uploads/" . $file_to_remove);
} else {
$this->listFiles();
}
}
I have case like this :
1. User choose a or lot of file images on first chance, e-g 2 files image.
2. After loaded, user choose a file again
3. But, the image that was successfully upload just one last file chosen. The two files in not uploaded ?
In my controller, I use insert batch. So i must to save all information into database in array(array(),array());
Is it possible to upload those file like triggered ? So, if user choose two files and then choose again another file, so on so on, all the choosed file will be uploaded.
I want to upload different images from different folders in a single file upload form submit.
When I click the upload button for the second time before clicking the submit button, file input field get replace with the latest selections.
Is it possible to append the selections till the submit is clicked.
My JS code displays all the selected file. But submits only the last selections
Here is my HTML
<form name="status-form" id="status-form" method="post" enctype="multipart/form-data">
<input type='file' name='file1[]' id="upload-image" multiple />
<input type='hidden' name='file2' value="aaaaaaaa" />
<div id="upload-img">
<output id="list"></output>
</div>
<br/>
<button type="submit" name="submit" class="btn btn-info" id="status-btn">Send It!</button>
</form>
Here is my JS
var allImages = [];
if (window.FileReader) {
document.getElementById('upload-image').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0; i < files.length; i++) {
var f = files[i];
var reader = new FileReader();
reader.onload = (function(f) {
return function(e) {
document.getElementById('list').innerHTML = document.getElementById('list').innerHTML + ['<img src="', e.target.result,'" title="', f.name, '" width="150" class="image-gap" />'].join('');
};
})(f);
reader.readAsDataURL(f);
}
var formData = $('form').serializeArray();
console.log(formData);
$.ajax({
type:'POST',
url: 'temp.php',
data:formData,
success:function(data){
//code here
},
error: function(data){
//code here
}
});
console.log(folder);
$('#upload-img').addClass('image-div');
}
And my PHP is just a var_dump for the moment
if (isset($_POST['submit'])) {
var_dump($_FILES['file1']);
var_dump($_POST['file2']);
}
You can try this:
Select file using browse field
call a method (setImage()) on onchange of this browse field
and in setImage():
function setImage(){
// Get the src value of browse field
// Create a new hidden browse field with src value of above browse
// field
// And set blank value of src of first one browse field
}
The idea is you select an image n times, the above method will create n hidden browse field in your html.
For example: If you select three images, then there will be four browse fields.
1 Shown to you
Other three are hidden
Now press submit and in server side you will get 4 file fields one with empty file and other three with files.
Ignore empty one and upload other three images.
With the hint given by Rahul I was able to make it work.
Here is the answer
JS File
var uploadImage = 0;
$( document ).ready(function() {
uploadImage = Math.floor(Date.now() / 1000);
});
if (window.FileReader) {
document.getElementById('upload-image').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0; i < files.length; i++) {
var f = files[i];
var reader = new FileReader();
reader.onload = (function(f) {
return function(e) {
document.getElementById('list').innerHTML = document.getElementById('list').innerHTML + ['<img src="', e.target.result,'" title="', f.name, '" width="150" class="image-gap" />'].join('');
$('<input>').attr({
type: 'hidden',
id: uploadImage++,
name: uploadImage++,
value: e.target.result
}).appendTo('form');
console.log(e.target.result);
};
})(f);
reader.readAsDataURL(f);
}
$('#upload-img').addClass('image-div');
}
PHP Code
if (isset($_POST['submit'])) {
define('UPLOAD_DIR', 'images/');
$patterns = array('/data:image\//', '/;base64/');
foreach ($_POST as $key => $value) {
if (preg_match('/^(0|[1-9][0-9]*)$/', $key)) {
$imageData = explode(',', $value, 2);
$type = preg_replace($patterns, '', $imageData[0]);;
if (count($imageData) > 1) {
$img = str_replace($imageData[0].',', '', $value);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.'.$type;
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
}
}
}
}
HTML Code
<form name="status-form" id="status-form" method="post" enctype="multipart/form-data">
<input type='file' name='file1[]' id="upload-image" multiple />
<div id="upload-img">
<output id="list"></output>
</div>
<br/>
<button type="submit" name="submit" class="btn btn-info" id="status-btn">Send It!</button>
</form>
I have some working code but want to add upload image field but with no success.
My current code is:
Form:
<form id="add_product_form" enctype="multipart/form-data">
<input id="uploadFile" type="file" name="image" class="img" /><br />
<input id="status" type="checkbox" checked /><br />
<input id="product" type="text" /><br />
<label for="button" id="response"></label>
<input type="button" id="button" value="Добави" /><br />
</form>
jQuery:
<script type="text/javascript">
$('document').ready(function(){
$('#button').click(function(){
var image = $('input[type=file]').val().split('\\').pop();
function chkb(bool){ if(bool) return 1; return 0; } var status=chkb($("#status").is(':checked'));
if($('#product').val()==""){ alert("enter name"); return false; } else { var product = $('#product').val(); }
jQuery.post("products_add_process.php", {
image: image,
status: status,
product: product
},
function(data, textStatus) {
$('#response').html(data);
if(data == 1){
$('#response').html("OK");
$('#response').css('color','green');
document.getElementById("add_product_form").reset();
} else {
$('#response').html("Not OK");
$('#response').css('color','red');
}
});
});
});
</script>
products_add_process.php:
<?php
$image_name = $_FILES['image']['name'];
$image_type = $_FILES['image']['type'];
$image_size = $_FILES['image']['size'];
$image_tmp_name = $_FILES['image']['tmp_name'];
$status = $_POST['status'];
$product = $_POST['product'];
if($image_name == '') {
echo "<script>alert('Select image')</script>";
exit();
} else {
$random_digit=rand(0000000000,9999999999);
$image=$random_digit.$image_name;
move_uploaded_file($image_tmp_name,"uploads/$image");
$query=mysql_query("INSERT INTO products(product, image, status) VALUES ('$product', '$image', '$status')");
if(mysql_affected_rows()>0){
$response = 1;
echo "1";
} else {
$response = 2;
echo "2";
}
}
?>
I put alert 'Select image' and then understand that $image_name is empty and maybe somewhere have to put some code to say that I want to send DATA TYPE. I try to add to form enctype="multipart/form-data" but won't work.
Where and what have to add in existing code to make sending data, without making very big changes because this code have in a lot of files and will be difficult to edit big part of codes.
Maybe have to add that form and jQuery are in php file which is called in other mother file and structure is something like this:
products.php /call products_add.php/
products_add.php /where is the form and jQuery/
products_add_process.php /called from products_add.php to upload data/
p.s. Sorry if I don't explain my problem well but I'm from soon at stackoverflow and still learning how to post my questions :)
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(),
i have a uploading script and works like a charm but i wanted to expand it with not only uploading one image, but several images. That resulted in my script only uploading the last image and not all of them with the text included with them in the textarea. i just can't figure out why it just won't upload all images.
my upload.php:
<?php // Start a session for error reporting session_start(); // Call our connection file require( "includes/conn.php"); // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds
all the valid image MIME types $valid_types=a rray( "image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file[ 'type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that 's easy to read
// I used this function during debugging but it serves no purpose at run time for this example
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
// Set some constants
// This variable is the path to the image folder where all the images are going to be stored
// Note that there is a trailing forward slash
$TARGET_PATH = "content/uploads/";
// Get our POSTed variables
$fname = $_POST['fname '];
$lname = $_POST['lname '];
$image = $_FILES['image '];
// Sanitize our inputs
$fname = mysql_real_escape_string($fname);
$lname = mysql_real_escape_string(nl2br($lname));
$image['name '] = mysql_real_escape_string($image['name ']);
// Build our target path full string. This is where the file will be moved do
// i.e. images/picture.jpg
$TARGET_PATH .= $image['name '];
// Make sure all the fields from the form have inputs
if ( $fname == "" || $lname == "" || $image['name '] == "" )
{
$_SESSION['error '] = "All fields are required";
header("Location: indexbackup.php");
exit;
}
// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!is_valid_type($image))
{
$_SESSION['error '] = "You must upload a jpeg, gif, or bmp";
header("Location: indexupload.php");
exit;
}
// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($TARGET_PATH))
{
$_SESSION['error '] = "A file with that name already exists";
header("Location: indexupload.php");
exit;
}
// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($image['tmp_name '], $TARGET_PATH))
{
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql="insert into people (fname, lname, filename) values ('$fname', '$lname', '" . $image[ 'name'] . "')"; $result=m ysql_query($sql)
or die ( "Could not insert data into DB: " . mysql_error()); header( "Location: indexupload.php"); exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod
the directory to be writeable $_SESSION[ 'error']="Could not upload file. Check read/write persmissions on the directory" ; header( "Location: indexupload.php"); exit; } ?>
and this is the page that let's me select the files and fill in the text area:
var abc = 0; // Declaring and defining global increment variable.
$(document).ready(function () {
// To add new input file field dynamically, on click of "Add More Files" button below function will be executed.
$('#add_more').click(function () {
$(this).before($("<div/>", {
id: 'filediv'
}).fadeIn('slow').append($("<input/>", {
name: 'image',
type: 'file',
id: 'file'
}), $("<br/><br/>")));
});
// Following function will executes on change event of file input to select different file.
$('body').on('change', '#file', function () {
if (this.files && this.files[0]) {
abc += 1; // Incrementing global variable by 1.
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd" + abc).append($("<img/>", {
id: 'img',
src: 'images/x.png',
alt: 'delete'
}).click(function () {
$(this).parent().parent().remove();
}));
}
});
// To Preview Image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
}
;
$('#upload').click(function (e) {
var name = $(":file").val();
if (!name) {
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
<div id="maindiv">
<div id="formdiv">
<h2>Upload en delete pagina</h2>
<?php
if (isset($_SESSION['error'])) {
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="upload2.php" method="post" enctype="multipart/form-data">
<label>Merk</label>
<input type="text" name="fname" style="width:250px;"/><br />
<label>beschrijving</label>
<textarea name="lname" style="width:250px;height:150px;"></textarea><br />
<label>Upload afbeelding</label>
<div id="filediv"><input type="file" name="image" id="file"/></div>
<input type="hidden" name="MAX_FILE_SIZE" value="5000000" />
<br /><br /><p>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<br /><br />
<input type="submit" value="Upload" name="submit" id="submit" class="upload" style="left:200px;"/>
</p>
</form>
<br /><br />
<p>
<form action="delete_multiple.php" method="post">
Wil je auto's van de site halen?
<input type="checkbox" name="formverkocht" value="Yes" />
<input type="submit" name="formSubmit" value="Submit" />
</form>
</p>
</div>
</div>
thanks in advance guys!
You have spaces in ALL of your post parameters:
$fname = $_POST['fname '];
^--
That space DOES count for naming purposes, and is NOT the same as 'fname'. The keys in _POST/_GET must match EXACTLY what you have in the html:
<input type="text" name="foo"> -> $_POST['foo'] // note the LACK of a space
<input type="text" name="bar "> -> $_POST['bar '] // note the space