upload image with ajax and pass muti parameter - javascript

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(),

Related

convert php image upload script to json response

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

Krajee Bootstrap File Input, ajax, codeigniter, upload trigger file with another data in one form

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.

FILE["file1"] is not set through AJAX

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);

uploading files through html form using javascript calling php

I have an HTML form in which I have to upload 3 files.
I have to call a create.js script after form submission which uses getElementById to format the input in desired way. Then it uses a xmlHTTPRequest to call create.php which inserts the form data into mysql database, and in the mean time fetches some data that it sends back to create.js using json_encode.
So I don't use the form action attribute but instead use the onClick attribute on my Submit button to call create.js.
But I have to upload my 3 files also on clicking Submit. I tried using $_FILE['file1']['name'] and other $_FILE[][] variables, where I use <input type="file" name="file1" id="file1"> to uplaod my first file but it gave the following error:
Undefined index: file1 in C:\xampp\htdocs\mywebsite\sites\all\themes\danland\create.php on line 77
So how can I incorporate my code for storing uploaded files on my server in the same php that returns xmlhttp.responseText to my .js file ?
I also tried putting my code of uploading in upload.php and called it using <form action="the/correct/path/upload.php"> besides using onClick = "my_create.js_function()" in my submit button but it did not work
Note that I have read html upload using ajax and php and know that I cannot upload my file using xmlhttprequest, but I am not trying to do that. I want my xmlhttprequest to fetch data after submit is clicked and my submit button to also store my files.
My HTML form is:
<script src="http://localhost/mywebsite/sites/all/themes/danland/src/create.js">
</script>
<script type="text/javascript" src="http://localhost/mywebsite/sites/all/themes/danland/src/datepickr.js"></script>
<script>
window.onload = create_new_project_getoptions();
</script>
<div class="searchinterfacecontainer">
<p id="my_first_para"></p>
<p id="this_is_my_new_para"></p>
<h2>Enter Details</h2>
<form id="create_projectform1" name="create_projectform1" method="POST" enctype="multipart/form-data" action="http://localhost/mywebsite/sites/all/themes/danland/create_new_project_upload.php">
<input type="text" name="project_id" id="project_id" required/>
<input type="text" name="project_name" id="project_name" required/>
<input id="project_start_date" onClick="new datepickr('project_start_date')" required/>
<select id="project_geography" name="project_geography">
<option value="">Select Country </option>
</select><br/>
<input type="file" name="file1" id="file1">
<input type="file" name="file2" id="file2">
<input type="file" name="file3" id="file3">
<div class="searchinterfacebuttons"><input type="submit" class="searchinterfaceform1go" value="Search" onClick="create_new_project()"/> <button class="searchinterfaceform1go" type="reset" value="Reset"> Reset </button></div>
</form>
</div>
My create.js:
function create_new_project( )
{
alert("entered");
var project_id = document.getElementById("project_id").value;
var project_name = document.getElementById("project_name").value;
var project_start_date = document.getElementById("project_start_date").value;
// some more getElementByID
var error_para = document.getElementById("my_first_para");
var my_error = "";
error_para.innerHTML = my_error;
// some string manipulation with the above defined variables
project_start_date = date_fixer(project_start_date);
project_completion_date = date_fixer(project_completion_date);
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var params = "project_id=" + project_id + "&project_name=" + project_name ; // + some more parameters
var url = "http://localhost/mywebsite/sites/all/themes/danland/create.php";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var val = xmlhttp.responseText;
//alert(val);
var jsonData = JSON.parse(val);
// some manipulation with json data
var answer = document.getElementById("this_is_my_new_para");
answer.innerHTML = jsonData;
}
}
xmlhttp.send(params);
}
function date_fixer(my_date)
{
// code here that works fine
}
My create.php:
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'this_user');
define('DB_PASSWORD', 'this_password');
define('DB_DATABASE', 'mywebsite');
$project_id = $_POST["project_id"];
$project_name = $_POST["project_name"];
$project_start_date = $_POST["project_start_date"];
// some more $_POST[]
$date_status1 = date_fixer($project_start_date);
$date_status2 = date_fixer($project_completion_date);
//echo "date status 1 is $date_status1 and date_status2 is $date_status2";
if ( $date_status1 == -1 || $date_status2 == -1 ) // not a valid date
{
echo "The date was not in correct format. Please use the date picker";
}
else
{
try
{
$db = new PDO('mysql:host=' .DB_SERVER . ';dbname=' . DB_DATABASE . ';charset=utf8', DB_USERNAME, DB_PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query_geography = "INSERT into " . DB_TABLE . "( projectID, project_name, start_date) values ( (:pid), (:pname), (:sdate))";
$parameters1 = array(':pid'=>$project_id, ':pname'=>$project_name, ':sdate'=>$project_start_date);
$statement1 = $db->prepare($query_geography);
$statement1->execute($parameters1);
}
catch(Exception $e)
{
echo 'Exception -> ';
var_dump($e->getMessage());
}
}
function date_fixer($my_date)
{
// valid function that works fine
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file1"]["name"]);
$extension = end($temp);
print_r($temp);
print_r($extension);
if ( ( ($_FILES["file1"]["type"] == "image/gif") || ($_FILES["file1"]["type"] == "image/jpeg") || ($_FILES["file1"]["type"] == "image/jpg") || ($_FILES["file1"]["type"] == "image/pjpeg") || ($_FILES["file1"]["type"] == "image/x-png") || ($_FILES["file1"]["type"] == "image/png") ) && ($_FILES["file1"]["size"] < 20000) && in_array($extension, $allowedExts) )
{
if ($_FILES["file1"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file1"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file1"]["name"] . "<br>";
echo "Type: " . $_FILES["file1"]["type"] . "<br>";
echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file1"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file1"]["name"]))
{
echo $_FILES["file1"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file1"]["tmp_name"], "upload/" . $_FILES["project_file1"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["project_file1"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
to get values from $_FILE you have to set form enctype to multipart/form-data.
if you want to read the value of file field then in jQuery simply write $('#id_filefield').val();

Weird MIME type on ajax upload in Codeigniter

I always got an invalid file type error in uploading csv file in codeigniter. I already googled for possible mime types for csv and still nothing works. so I bother echoing the echo $_FILES['userfile']['type']; and I got this MIME type : 'application/force-download'. Below is a snippet from the controller and a snippet from the view
Controller:
public function upload_file()
{
$status = "";
$msg = "";
$file_element_name = 'userfile';
if (empty($_POST['title']))
{
$status = "error";
$msg = "Please enter a title";
}
if ($status != "error")
{
$config['upload_path'] = './uploads/csv_list/';
$config['allowed_types'] = 'gif|jpg|png|doc|txt|.csv';
$config['max_size'] = 1024 * 8;
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$status = "success";
$msg = "File successfully uploaded";
}
#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
View:
<input type="text" name="title" id="title" value="a" style ="display:none"/>
<p>
<input type="text" name="title" id="title" value="a" style ="display:none"/>
<label for="userfile">Upload CSV File</label>
<input type="file" name="userfile" id="userfile" size="20" />
<input type="submit" name="submit" id="submit" value ="Upload"/>
</p>
<script>
$(function () {
$('#upload_file').submit(function (e) {
e.preventDefault();
$.ajaxFileUpload({
url: '../upload/upload_file/',
secureuri: false,
fileElementId: 'userfile',
dataType: 'json',
data: {
'title': $('#title').val()
},
success: function (data, status) {
if (data.status != 'error') {
$('#files').html('<p>Reloading files...</p>');
// refresh_files();
// $("#userfile").replaceWith("<input type=\"file\" id=\"userfile\" size = \"20\" />");
$('#files').html('File Uploaded');
// $('#title').val('');
}
alert(data.msg);
}
});
return false;
});
});
</script>
The problem here is that different web browser gets different ideas on what type a file is. Since CodeIgniter's upload class is dependent of file types, this can get messy.
I followed several instruction to add more types to the fields in the config/ but neither did the trick.
I ended up with allowing all types $config['allowed_types'] = '*' and validated like this instead:
if (in_array(end(explode('.', $str_file_name)), array('php')))
return FALSE;
or in your case:
$arr_validate = array('gif', 'jpg', 'png', 'doc', 'txt', 'csv');
if ( ! in_array(end(explode('.', $str_file_name)), $arr_validate))
return FALSE;

Categories

Resources