I am using the Jquery Form plugging to try and upload a picture to my mysql DBMS. I use the JqueryForm ajaxForm() call to do this. It calls a php file on my server and that script puts the file into the database. I then attempt to get that file out of the database in the same script. I guess the nuts and bolts of how I do it is irrelevant. I really want to know how I would get a picture back from an ajax call using the AjaxForm call from the jqueryForm pluggin. Does anybody have an example of how to do this using that pluggin? I am a little lost...
<script type="text/javascript" src="jquery.form.js"></script>
<script>
$(document).ready(function () {
$('#profilepicbutton').live('change', function () {
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#registerpt3").ajaxForm({
target: '#preview',
success: function (data) {
$("#preview").html('');
$("#preview").append("<img src=" + data + "></img>");
}
}).submit();
});
});
</script>
Now, On the jquery form pluggin site, there is a page in particular that has instructions for file uploads...
http://jquery.malsup.com/form/#file-upload
The example that they give is a little blank...
<textarea>
for (var i=0; i < 10; i++) {
// do some processing
}
</textarea>
Now, what am I supposed to do with that? Why am I looping through some data structure? If you look on there page, you will see they are remarkable brief in their instructions of what to do. Anybody have any tutorials or advice? Thanks.
UPDATE PHP Code
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['profilepicinput']['name'];
$size = $_FILES['profilepicinput']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['profilepicinput']['tmp_name'];
$fp = fopen($tmp, 'r');
$data = fread($fp, filesize($tmp));
$data = addslashes($data);
fclose($fp);
values('$email', '$tmp')");
if(mysql_query("insert into Personal_Photos (Email, Pics) values('$email', '$data')"))
{
$query="select Pics, MAX(ID) from Personal_Photos where Email='$email'";
$result=mysql_query($query) or die("Error: ".mysql_error());
$row=mysql_fetch_array($result);
$mime = 'image/yourtype';
$base64 = base64_encode($contents);
$uri = "data:$mime;base64,$base64";
header("Content-type: image/jpg");
print($row['Pics']);
}
else
{
die('Invalid query: ' . mysql_error());
echo "failed";
}
}
else
echo "Image file size max 1 MB. Image Size:"+$size;
}
else
echo "Invalid file format..";
}
else
echo "Please select image..! Bull shit".$email;
exit;
}
If I understand your question right, you can create a so called data URI.
In PHP it's quite simple:
$mime = 'image/yourtype';
$base64 = base64_encode($contents);
$uri = "data:$mime;base64,$base64";
And pass this as string in the ajax reponse to be directly entered as you outlined in your question.
Hopefully this helps, I'm not fluent with jqueryform.
Related
I'm generating CSV file from the table data. The table records are in millions. The problem is when i click the EXPORT To CSV button it takes more than 6 minutes to generate the CSV file and my server throws timeout error after 6 minute.
UPDATE: I know i can increase the timeout time but i need to optimize the below script and QUERY!
Function For Exporting The Users to CSV
// Function for exporting all Quiz Users Leads to CSV
public function executeUserExportLeads($request) {
$this->export = true;
$this->pager = new myPropelPager('BtqUser', 9999999);
$this->pager->setCriteria(btqAdminBtqUserPeer::getBtqUsersForExport());
$this->pager->setPeerMethod('doSelectStmt');
$this->pager->setAction('newadmin/users');
$this->pager->setPage($request->getParameter('page', 1));
$this->pager->init();
//Generating CSV in server and giving user the CSV file for download
if($this->pager->getResults() > 0){
$filename = "userleads".".csv";
unlink($filename);
$uploaddir = sfConfig::get('sf_upload_dir');
$path = $uploaddir ."/" . $filename;
fopen($path , 'a');
$handle = fopen($path, 'w+');
//set column headers
$fields = array('Date', 'Name', 'Email', 'Lead From', 'State', 'Phone No',"\r\n");
fwrite($handle, implode(',',$fields));
//output each row of the data, format line as csv and write to file pointer
foreach($this->pager->getResults() as $row){
$lineData = array(date('M-d-Y', strtotime($row['schedule_date'])), $row['name'], $row['email'] , $row['lead_from'], $row['state'], $row['telefon'],"\r\n");
fwrite($handle, implode(',',$lineData));
}
fclose($handle);
$result_array = array('fileURL' => 'http://this-site.com/uploads/'.$filename);
return $this->renderText(json_encode($result_array));
}
exit;
}
Query Export ( this fetches all users record for exporting to csv ):
public static function getBtqUsersForExport() {
$criteria = new Criteria();
$criteria->clearSelectColumns();
$criteria->addSelectColumn("btq_user.id as id");
$criteria->addSelectColumn("btq_user.name as name");
$criteria->addSelectColumn("btq_user.email as email");
$criteria->addSelectColumn("btq_user.lead_from as lead_from");
$criteria->addSelectColumn("btq_user.telefon as telefon");
$criteria->addSelectColumn("btq_user.datain as datain");
$criteria->addSelectColumn("state.state as state");
$criteria->addSelectColumn("lead_schedule.id as schedule_id");
$criteria->addSelectColumn("lead_schedule.created_at as schedule_date");
$criteria->addJoin(self::STATE_ID, StatePeer::ID, Criteria::LEFT_JOIN);
$criteria->addJoin(self::ID, LeadSchedulePeer::LEAD_ID, Criteria::LEFT_JOIN);
$criteria->addJoin(self::ID, BtqUserTrackBlogVideoPeer::USER_ID, Criteria::LEFT_JOIN);
$criteria->addGroupByColumn(self::EMAIL);
$criteria->add(BtqUserPeer::IS_DUMMY_DETAIL, "1", Criteria::NOT_EQUAL);
$criteria->addDescendingOrderByColumn(self::DATAIN);
return $criteria;
}
Ajax for the request:
<script>
function move() {
var hidden = document.getElementById("myProgress");
hidden.classList.remove("hidden");
var elem = document.getElementById("myBar");
var width = 1;
var id = setInterval(frame, 5000);
function frame() {
if (width >= 100) {
clearInterval(id);
var hidden = document.getElementById("myProgress");
hidden.classList.add("hidden");
} else {
if(width>100){
}else{
width++;
elem.style.width = width + '%';
}
}
}
$('#exportCSV').submit(function(event){
event.preventDefault();
});
$.ajax({
data: {export: "Export To CSV"},
type: 'POST',
url: 'userExportLeads',
success: function(result){
console.log(result);
var data = JSON.parse(result);
clearInterval(id);
$('#myBar').css('width','100%');
$('#myProgress').delay(5000).fadeOut();
location.href = data.fileURL;
}
});
}
</script>
And the below is form code:
<form id="exportCSV" action="<?php echo url_for('newadmin/userExportLeads'); ?>" method="POST">
<input type="submit" onclick="move()" name="export" value="Export To CSV" />
</form>
</div>
<br/>
<div id="myProgress" class="hidden" align="left">
<div id="myBar"></div>
</div>"
If there is anything else required i can share it.
Thanks
I'm not sure whether this is major problem and effects on export execution time, but it's better to refactor it
if ($this->pager->getResults() > 0) {
foreach ($this->pager->getResults() as $row) {
}
}
to this
$result = $this->pager->getResults();
if ($result.count() > 0) { //I'm not sure how myPropelPager works and what is the type of $result. Let's hope it is Countable
foreach ($result as $row) {
}
}
I also don't know what $this->pager->getResults() does. In worst case calling it two times you're executing DB query two times.
Also I'm in hope that $result is a Cursor, not array containing all results.
My optimization may help to reduce time and memory usage, but I'm not sure.
Anyways after all optimizations, if you're exporting millions of rows, you'll met this problem again. The best practice is to detach this procedure from web-server context and do in background with something like Gearman in background.
I agree with the recommendation in the comments that switching to raw SQL is probably the best bet.
Even if you don't do that, figure out what SQL Propel is running, and there may be some optimizations you can do. In doctrine you'd do that with echo $query->getSqlQuery(); I'm not familiar with how to do it in Propel. You may also be able to connect to MySQL while this slow query is running and SHOW FULL PROCESSLIST should show you the query that's running.
Prefix that query with EXPLAIN and you can see how MySQL's query plan; EXPLAIN SELECT isn't very intuitive to understand if you haven't used it before, but there are good guides online.
My problem is that my script doesnt upload the pic on serv and insert it into database when i use ajax submit for some reason. If i submit form with php action="file.php" it works. Here are my ajax script and php one.I dont see where the problem is and why it works with php submit and not working with ajax. Thnx in advance.
<script>
$(function() {
//twitter bootstrap script
$("button#submit").click(function(){
$.ajax({
type: "POST",
url: "engine/app/process.php",
data: $(\'form.edit\').serialize(),
dataType:\'json\',
success: function(data){
$("#bday").html(data.a)
$("#locatie").html(data.b)
$("#descriere").html(data.c)
$("#interes").html(data.d)
$("#status").html(data.e)
$(".img").html(data.f)
$("#myModal").modal(\'hide\');
},
error: function(){
alert("failure");
}
});
});
});
</script>
php script
<?php
require_once('../core/dbconfig.php');
$dbc = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASS, DB_NAME);
$nume=$_POST['nume'];
$bday=$_POST['bday'];
$locatie=$_POST['locatie'];
$status=$_POST['status'];
$interese=$_POST['interese'];
$despre=$_POST['descriere'];
$id_user=$_POST['id_user'];
$query="Update `users` SET username='$nume',bday='$bday',Locatie='$locatie',Relatie='$status',Interese='$interese',Descriere='$despre' where id='$id_user' ";
$result=mysqli_query($dbc,$query) or die("query failed: " . mysqli_error($dbc));
$path = '../../images/users/'.$id_user.'/';
if(!is_dir($path)){
mkdir($path,0755);
}
$valid_formats = array("jpg", "png", "gif", "bmp", "jpeg", "JPG");
$name = $_FILES['img1']['name'];
$size = $_FILES['img1']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
/*$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;*/
$actual_image_name=$id_user.'.'.$ext;
$tmp = $_FILES['img1']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$queryz="Insert into Galerie (ID_User,Poza,Poza_Profil) VALUES ('$id_user','$actual_image_name',1)";
$resultz=mysqli_query($dbc,$queryz) or die("query failed: " . mysqli_error($dbc));
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
echo json_encode(array("a" => $bday, "b" => $locatie,"c" => $despre,"d" => $interese,"e" => $name,"f" => ""));
?>
The serialize method puts your form fields data in a string complying to the application/x-www-form-urlencoded content type used to submit forms to servers for processing, while files are submitted in requests encoded in the multipart/form-data content type, so, serialize ignores file inputs.
You should use formData
var form = new FormData(document.getElementById('your_frm_id'));
var file = document.getElementById('img1').files[0];
if (file) {
$('#sent_progress').show();
form.append('img1', file);
}
In ajax use
data: form,
Read More here https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
Or you can use some Jquery Plugin to upload your file with form
hope it will help
With only Ajax request you can't upload the file to the server. A Better option is use jQuery Form
This links also includes some example codes, follow the documentation and achieve what you want.
Take a look how to implement jQuery Form plugin, on Ajax based image upload
This is the js script at the bottom of my wp post.
<script type="text/javascript" src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
var id = 'downloadid';
var data_from_ajax;
$.post('download.php', {id : id}) .done(function(data) {
data_from_ajax = data;
});
function hey() {
document.write(data_from_ajax);
}
</script>
Function hey was being called from a link OnClick function. When using this, the page would successfully perform the php code on download php (update a db then download a file) although it would clear the current page I was on. What I wanted to do was perform the php and keep the current page template. So next I tried using
document.getElementById("download").innerHTML = data_from_ajax;
instead of document.write. I made a div with the id download. Now when I click it, it simply won't perform the php. when I replace the data_from_ajax with a string, it gladly puts it in the div though.
Any help would be great.
EDIT:
my html is
download
<div id='download'> </div>
http://jsfiddle.net/7smJE/
From PHP code which you've provided, I think you should replace document.write() in your code with $('#download').html(). This way you don't need to put the returned result in your download div anymore because when PHP page gets loaded it'll do this for you and you have to put your $.post in hey() function too because you need this to perform when your link gets clicked.
PHP:
<?php
$fileid = $id;
if (is_file('d84ue9d/' . $fileid . '.apk'))
{
$ip = $_SERVER['REMOTE_ADDR'];
$con=mysqli_connect("localhost","docvet95_check","%tothemax%","docvet95_downcheck");
$result = mysqli_query($con,"SELECT * FROM `download-check` where ip = '$ip'");
while ($row = mysqli_fetch_array($result))
{
$files = $row['files'];
$downloads = $row['downloads'];
}
if ($downloads > 4)
{
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%61%6C%65%72%74%28%27%59%6F%75%5C%27%76%65%20%64%6F%77%6E%6C%6F%61%64%65%64%20%66%69%76%65%20%6F%72%20%6D%6F%72%65%20%66%69%6C%65%73%2E%20%46%6F%72%20%72%69%67%68%74%20%6E%6F%77%2C%20%74%68%69%73%20%69%73%20%6F%6B%61%79%2E%20%49%6E%20%74%68%65%20%66%75%74%75%72%65%2C%20%79%6F%75%20%77%69%6C%6C%20%6E%65%65%64%20%74%6F%20%63%6F%6D%70%6C%65%74%65%20%61%20%73%75%72%76%65%79%20%69%6E%20%6F%72%64%65%72%20%74%6F%20%63%6F%6E%74%69%6E%75%65%20%64%6F%77%6E%6C%6F%61%64%69%6E%67%2E%20%54%68%61%6E%6B%20%79%6F%75%20%66%6F%72%20%75%73%69%6E%67%20%6F%75%72%20%77%65%62%73%69%74%65%27%29%3B%20%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%2F%61%70%6B%73%2F%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
}
else
{
$downloadq = $downloads + 1;
$there = $result->num_rows;
if ($there <1)
{
$addidnip = mysqli_query($con,"INSERT INTO `download-check` (ip, files, downloads) VALUES ('$ip', '$fileid', 1)");
}
else
{
$idtoarray = explode(",", $files);
if (!in_array($fileid, $idtoarray))
{
array_push($idtoarray, $fileid);
$newfile = implode(",", $idtoarray);
$adddw = mysqli_query($con,"UPDATE `download-check` SET downloads=$downloadq, files='$newfile' where ip = '$ip'");
}
}
print "<script type=\"text/javascript\">";
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
print "</script>";
}
}
else
{ echo 'Whoops, looks like we couldn\'t find that file. You could try searching for it?'; }
?>
JavaScript:
var id = 'downloadid';
var data_from_ajax;
function hey() {
$.post('download.php', {id : id});
}
But I recommend you to return the exact data from your PHP without any extra tag and then use it this way:
var id = 'downloadid';
function hey() {
$.post('download.php', {id : id}).done(function(data) {
$("#download").html(unescape(data));
});
}
From what I can see without the fiddle:
The hey function is probably fired before the done function is ready. Why don't you call hey() from within done()?
I am a newbie with codeigniter and I want to build a website using codeigniter framework. From first, it look fine I can use database, validation, email, session and then I try to attach a file and send with email :
$this->email->attach('/path/ofyour/constan/file.anything');
thats work too.
since that is a website I want my client to choose file they want to upload.
I try many method, and many of them tell to upload a file to server root and get the file_data, use file_data[file_patch]
$this->email->attach('file_data[file_path]');
the problem is:
since code igniter cant upload multiple data I must use plugin. I tried and its PAIN
I thing its not effective, upload data to server root and then to email?
it better to just get file_path of upload file and send them to email, how?
I build it with jquery mobile, what must I do?
Update
ok i decide to use uploadify i search every website and then i found here and my code is
uploadify.php
<?php
/*
* Functions taken from CI_Upload Class
*
*/
function set_filename($path, $filename, $file_ext, $encrypt_name = FALSE)
{
if ($encrypt_name == TRUE)
{
mt_srand();
$filename = md5(uniqid(mt_rand())).$file_ext;
}
if ( ! file_exists($path.$filename))
{
return $filename;
}
$filename = str_replace($file_ext, '', $filename);
$new_filename = '';
for ($i = 1; $i < 100; $i++)
{
if ( ! file_exists($path.$filename.$i.$file_ext))
{
$new_filename = $filename.$i.$file_ext;
break;
}
}
if ($new_filename == '')
{
return FALSE;
}
else
{
return $new_filename;
}
}
function prep_filename($filename) {
if (strpos($filename, '.') === FALSE) {
return $filename;
}
$parts = explode('.', $filename);
$ext = array_pop($parts);
$filename = array_shift($parts);
foreach ($parts as $part) {
$filename .= '.'.$part;
}
$filename .= '.'.$ext;
return $filename;
}
function get_extension($filename) {
$x = explode('.', $filename);
return '.'.end($x);
}
// Uploadify v1.6.2
// Copyright (C) 2009 by Ronnie Garcia
// Co-developed by Travis Nickels
if (!empty($_FILES)) {
$path = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
//$client_id = $_GET['client_id'];
$file_temp = $_FILES['Filedata']['tmp_name'];
$file_name = prep_filename($_FILES['Filedata']['name']);
$file_ext = get_extension($_FILES['Filedata']['name']);
$real_name = $file_name;
$newf_name = set_filename($path, $file_name, $file_ext);
$file_size = round($_FILES['Filedata']['size']/1024, 2);
$file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES['Filedata']['type']);
$file_type = strtolower($file_type);
$targetFile = str_replace('//','/',$path) . $newf_name;
move_uploaded_file($file_temp,$targetFile);
$filearray = array();
$filearray['file_name'] = $newf_name;
$filearray['real_name'] = $real_name;
$filearray['file_ext'] = $file_ext;
$filearray['file_size'] = $file_size;
$filearray['file_path'] = $targetFile;
$filearray['file_temp'] = $file_temp;
//$filearray['client_id'] = $client_id;
$json_array = json_encode($filearray);
echo $json_array;
}else{
echo "1";
}
i dont relly know what is going on here, like i said i am a newbie but i know something that $json_array, that array hold my data $filearray, that is data file uploaded. mission one complete
now my controller: upload.php
<?php
class Upload extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
}
/*
* Display upload form
*/
function index()
{
$this->load->view('view');
}
/*
* Handles JSON returned from /js/uploadify/upload.php
*/
function uploadify()
{
//Decode JSON returned by /js/uploadify/upload.php
$file = $this->input->post('filearray');
$data['json'] = json_decode($file);
$this->load->view('uploadify',$data);
}
}
/* End of File /application/controllers/upload.php */
my plan is send the data in onComplete function
my view :view.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<<head>
<meta charset="UTF-8">
<title>Uploadify and Codeigniter Tutorial</title>
<?php
$this->load->helper('html');
echo link_tag('http://uploadify_tutorial/uploadify/uploadify.css');
echo '<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>';
echo '<script src="http://localhost/uploadify_tutorial/uploadify/swfobject.js" type="text/javascript"></script>';
echo '<script src="http://localhost/uploadify_tutorial/uploadify/jquery.uploadify.v2.1.4.min.js" type="text/javascript"></script>';
$uploadpath="";
$uploadpath=str_ireplace($_SERVER['DOCUMENT_ROOT'],"", realpath($_SERVER['SCRIPT_FILENAME']));
$uploadpath=str_ireplace("index.php","",$uploadpath);
?>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("#upload").uploadify({
uploader: '<?php echo base_url();?>uploadify/uploadify.swf',
script: '<?php echo base_url();?>uploadify/uploadify.php',
cancelImg: '<?php echo base_url();?>uploadify/cancel.png',
folder: '/uploads',
scriptAccess: 'always',
multi: true,
'onError' : function (a, b, c, d) {
if (d.status == 404)
alert('Could not find upload script.');
else if (d.type === "HTTP")
alert('error '+d.type+": "+d.status);
else if (d.type ==="File Size")
alert(c.name+' '+d.type+' Limit: '+Math.round(d.sizeLimit/1024)+'KB');
else
alert('error '+d.type+": "+d.text);
},
'onComplete' : function (event, queueID, fileObj, response, data) {
//Post response back to controller
$.post('<?php echo site_url('upload/uploadify');?>',{filearray: response},function(info){
$("#target").append(info); //Add response returned by controller
});
}
});
});
</script>
</head>
<body>
<h1>Uploadify Example</h1>
<?php echo form_open_multipart('upload/index');?>
<p>
<label for="Filedata">Choose a File</label><br/>
<?php echo form_upload(array('name' => 'Filedata', 'id' => 'upload'));?>
Upload File(s)
</p>
<?php echo form_close();?>
<div id="target">
</div>
</body>
</html>
my view : uploadify
<html>
<ul>
<li>Extension: <?php echo $json->{'file_ext'};?></li>
<li>File Size: <?php echo $json->{'file_size'};?></li>
<li>File Path: <?php echo $json->{'file_path'};?></li>
</ul>
</html>
and then parsing that json_array variable to my view, that is the plans, but in reality that code doesn work the data is undefined
an error Trying to get property of non-object i use this code here, I suppose the problem is with json
i just want to use the data file uploaded if anyone can solve that problem please share it or send me CI+uploadify program to my email, if anyone expert about CI and Uploadify plugin please make the tutorial step by step how to use it, step by step, i think it would be great help for newbie like me
thanks....
my email :saya.dean#gmail.com
I'm not really clear on where you are running into a problem. 'that variable' will be the files you uploaded, yes? Create an array of the filepaths as they get uploaded and when the upload is done cycle through each for email attachment.
Have you checked other answers on the site? Maybe take a look here. But CI's documentation clearly states that you can use:
$this->email->attach('/path/to/that_file.jpg');
multiple times.
Update:
You can either try using the onUploadSuccess function in uploadify to append each file name to something that you can use later...
'onUploadSuccess' : function(file, data, response) {
alert('The file name is ' + file.name);
...
OR from within uploadify.php. From there you can store what you need for attaching after.
In your case I'd stick with modifying the uploadify.php. You'll have to give it a shot and post some code if you are stuck, but there are plenty of places to get some ideas like here and here
I need to take a CSV file from the client's machine and extract the data from it. I cannot save this CSV file, which is crucial (otherwise I would be laughing!). My PHP so far works like a charm:
upload.php
<?php
$file = $_FILES['file'];
if ($file['error'] === UPLOAD_ERR_OK) {
$ext = substr($file["name"], strrpos($file["name"], '.') + 1);
$maxSize = 3000000;
//Check file extension, MIME-type and size limit (3 MB).
if ($ext == "csv") {
if ($file["type"] == "text/csv" ||
$file["type"] == "text/comma-separated-values") {
if ($file["size"] < $maxSize) {
//CSV -> JSON
$fileAsArray = Array();
if (($handle = fopen($file["tmp_name"], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$fileAsArray[] = $data;
}
fclose($handle);
}
echo json_encode($fileAsArray);
die(json_encode($fileAsArray));
}
else {
echo "File size: ".$file["size"]."bytes<br>Limit: ".$maxSize." (3MB)";
}
}
else {
echo "MIME-type: ".$file["type"]."<br>Required: text/csv";
}
}
else {
echo "File Extension: ".$ext."<br>Required: csv";
}
}
else
die("Cannot upload");
?>
Ignore the echo. It was just so I knew it was actually working. However, I've been using jQuery with this website and can't figure out the code to properly get the form to submit the file and retrieve the JSON data back (fileAsArray) at the same time. Here is my HTML/jquery in index.html:
<script type="text/javascript">
var csvData = {}; //My global variable (two-dimensional JSON array)
$(document).ready(function(){
$("#upload").click(function(){
alert('test');
$.ajax({
type: "POST",
url: "upload.php",
data: "don't know what goes here",
dataType: "json",
success: function (data) {
alert(data); //Tried everything here too. :(
}
});
});
});
and HTML:
<form method="POST" action="upload.php" enctype="multipart/form-data" class="file_upload">
<input id="getFile" type="file" name="file">
<input value="Extract Data" id="upload" type="button">
</form>
I tried type="submit" as well, and a bunch of other things including just a 'form' tag and letting jQuery handle the POST... Thanks. If there is a better way to do this, please let me know :)
(I've been struggling with this for several days now... Having gone through many renditions of the code outlined below, I've stripped it down to its basics.)
If you want to upload CSV data through an Ajax post request, you must read the content of the file and insert it into the data: "don't know what goes here" field. Currently, only HTML5 browsers provides FileReader API that enables JavaScript to read the file, for Internet Explorer you must use a Flash-based solution.
I wrote a jQuery plug-in before that works with HTML5 browsers and jQuery. It would work with jQuery 1.4 - I am not sure about jQuery 1.5.