this code uploads csv file only but i want xls too? - javascript

<?php
include 'model.php';
$rs=new database();
if(isset($_POST["Import"])){
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$res=$rs->insert($emapData[0],$emapData[1],$emapData[2],$emapData[3],$emapData[4],$emapData[5]);
$result=mysql_fetch_array($res);
if(! $result )
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"result.php?msg=valid\"
</script>";
}
}
fclose($file);
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"result.php?msg=valid\"
</script>";
mysql_close($conn);
}
}
?>
this code only uploads csv file but i want to upload xls too with this code. if possible i want to upload all format of excel . and the rest of code is working fine and also i dont want to change the method.

Download PHPExcel
https://github.com/PHPOffice/PHPExcel
and create this function
function getDataFromExcel($filename)
{
$excel = PHPExcel_IOFactory::load($filename);
$sheet = $excel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$sheetData = $sheet->toArray(null, true, true, true);
return $sheetData;
}
It will return data in array
if you want to know the type of file use this method
function getFileType($key)
{
//Define type
$type = 'unknow';
if(isset($_FILES[$key])) {
$file = $_FILES[$key];
$fileType = $file['type'];
if (strrpos($fileType, 'csv')) {
$type = 'csv';
} else if (($fileType == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || ($fileType == 'application/vnd.ms-excel')) {
$type = 'excel';
}
}
return $type;
}

Related

How do I get a value that is returned by a php script in Ajax?

I need to get an array $data from the backend to the frontend in order to organize it for viewing. I can only find examples using jQuery Ajax.
<!DOCTYPE html>
<html>
<style>
.table_class{
display:none;
}
</style>
<script>
async function uploadFile() {
let formData = new FormData();
formData.append("file", fileupload.files[0]);
console.log(formData);
await fetch('file_ingest.php', {
method: "POST",
body: formData,
});
var test = document.getElementById("test");
test.innerText = ('The file has been uploaded successfully.');
//var returned_vals = JSON.parse(formData.responseText);
//console.log(returned_vals);
}
</script>
<body>
<input id="fileupload" type="file" name="fileupload" />
<button id="upload-button" onclick="uploadFile()"> Upload </button>
<p id = "test"></p>
</body>
</html>
I need to get an array $data from the backend to the frontend in order to organize it for viewing. I can only find examples using jQuery Ajax.
<?php
set_time_limit(120);
/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];
/* Choose where to save the uploaded file */
$location = "uploads/".$filename;
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) {
echo 'Success';
} else {
echo 'Failure';
$CSVfp = fopen("uploads/${filename}", "r");
if($CSVfp !== FALSE) {
while(! feoF($CSVfp)) {
$data = fgetcsv ($CSVfp, 1000, ",");
print json_encode($data);
//echo $data;
}
}
fclose($CSVfp);
<?php
set_time_limit(120); // if you need this you may have other problems
/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];
/* Choose where to save the uploaded file */
$location = "uploads/".$filename;
$response = [];
/* Save the uploaded file to the local filesystem */
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) {
$response['status'] = 'Files Save Success';
// read the file here, if it failed the upload and move
// there is no point trying to read it
if (($fp = fopen($location, "r")) !== FALSE) {
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
$response['data'][] = $data
}
fclose($fp);
}
} else {
$response['status'] = 'File Save Failure';
}
// now you can return either an error or a success and data
echo json_encode($response);
Now you need to checnge the javascript to look for the status in the right place and unload the row data from the the right place

Problem in uploading file in Folder in laravel 5.3?

I am trying to upload image in laravel but i am getting error when I am uploading image in folder, When I am uploading image and clicking on submit button, it's giving me problem in uploading file, i think there are error in this line...
move_uploaded_file($imageName, $moveable_file);
here are my usercontrolle.php file
public function dropzone(Request $request)
{
$user = Auth::user()->toArray();
$user_id = $user['id'];
$type = 'photo';
$type_id=0;
$data = $_FILES["image"];
//dd($data);
$doc_id = $_POST["doc_id"];
$doc_name = $_POST["doc_name"];
if($doc_id)
{ $img_id=$doc_id;
$img_name=$doc_name;
$response = $this->userService->deleteDocument($img_id,$img_name,$user_id,$type,$type_id);
}
// $image_array_1 = explode(";", $data);
// $image_array_2 = explode(",", $image_array_1[1]);
// $data = base64_decode($image_array_2[1]);
$storage_path = env('DOCUMENT_STORAGE_PATH');
$profile_upload_dir = str_replace(["/","\\"], [DIRECTORY_SEPARATOR,DIRECTORY_SEPARATOR], $storage_path);
if($type_id != '0'){
$destination_path = $profile_upload_dir . $user_id ."\\". $type."\\". $type_id;
$destination_path = str_replace(["/","\\"], [DIRECTORY_SEPARATOR,DIRECTORY_SEPARATOR], $destination_path);
}else{
$destination_path = $profile_upload_dir . $user_id ."\\". $type;
$destination_path = str_replace(["/","\\"], [DIRECTORY_SEPARATOR,DIRECTORY_SEPARATOR], $destination_path);
}
if(!is_dir($destination_path)) {
mkdir($destination_path, 0777,true);
}
$imageName = time() . '.png';
// dd($imageName);
$moveable_file = str_replace(["/","\\"], [DIRECTORY_SEPARATOR,DIRECTORY_SEPARATOR], $destination_path.'\\'.$imageName);
//dd($moveable_file);
move_uploaded_file($imageName, $moveable_file);
// file_put_contents($moveable_file, $data);
//$image_file = addslashes(file_get_contents($moveable_file));
$user = Auth::user()->toArray();
//dd($user);
$user_id = $user['id'];
$type_id = 0;
if(isset($photo['type_id']) && !empty($photo['type_id'])){
$type_id = $photo['type_id'];
}
//$photo['file']=$_FILES['photoimg'];
$photo['type']='photo';
$result = $this->userService->storeUserDocuments($imageName, $photo['type'], $type_id, $user_id);
// echo '<img src="data:image/png;base64,'.base64_encode($data).'" data-action="zoom" class="pull-left" style="height: 130px;width:130px;">';
}
You can also use image intervention to upload images.
First, install this on your laravel project using
composer require intervention/image
After installation open config/app.php and then add these in the $providers array.
Intervention\Image\ImageServiceProvider::class
Also, add the facade of this package to the $aliases array.
'Image' => Intervention\Image\Facades\Image::class
After this, you are ready to add images
Add this to your controller
use Intervention\Image\Facades\Image;
Here is a sample example of how to add images, use this in the controller
//Handle the user upload of avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time().'.'.$avatar->getClientOriginalExtension(); //use time to create file name
Image::make($avatar)->resize(300,300)->save( public_path('/images/'.$filename) );
$user->avatar = $filename;
//Handle the user upload of avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time().'.'.$avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300,300)->save( public_path('/images/'.$filename) );
$user->avatar = $filename;
// $user->save(); //To save the name of the file in the database
}
}

How to create tableau columns headers with no column data type using tableau web data connector?

I am trying to use tableau wdc for the first time using csv file .I also using type file of csv columns. But I dont want to use such type file. I want to use only csv file with tableau wdc.Can tableau know the csv column types with no data type properties?
<?php
$id = $_GET['id'];
$row = 1;
$csvdata = $csvtitle = $a = array();
if (($handle = fopen($id.".csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// $num = count($data);
if($row === 1){
$csvtitle = $data;
}else{
array_push($csvdata,$data);
}
$row++;
}
fclose($handle);
}
$csvtype = array();
$row1 = 1;
if (($handle = fopen($id.".txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$row1++;
$csvtype = $data;
}
fclose($handle);
}
?>
(function() {
var csvtitle = <?php echo json_encode($csvtitle); ?>;
var csvtype = <?php echo json_encode($csvtype); ?>;
var csvdata = <?php echo json_encode($csvdata); ?>;
var myConnector = tableau.makeConnector();
myConnector.getColumnHeaders = function() {
tableau.headersCallback(csvtitle, csvtype);
};
myConnector.getTableData = function(lastRecordToken) {
tableau.dataCallback(csvdata, false, false);
};
myConnector.init = function() {
tableau.initCallback();
if (tableau.phase == tableau.phaseEnum.interactivePhase) {
tableau.submit();
}
};
tableau.registerConnector(myConnector);
})();
There is already a CSV community provided connector. . It (internally) tries to guess at the data type just like Tableau. You could either use that connector or look at their code if it doesn't suite your needs.
Are you just trying to open a local CSV file here? You could just use the native connector instead and/or upload files directly to Tableau Server with a Creator license (2018.1 and above).

Canvas will not save server side PHP

I have a canvas which I need to save to a directory and store the URL in a database.
When I save the file without storing the URL in the database it works fine, and vice versa.
However, when I put the two together and specify the PHP file through AJAX, for some reason it doesn't recognise the session variable?
When I try to call the "success" on AJAX, nothing shows up. I get no response.
This could possibly be an easy fix! I think I've been staring at this code for too long.
JavaScript:
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'doodleupload.php',
type:'POST',
data:{ data:canvasData },
success: function(response){
alert(response);
//echo what the server sent back...
}
});
}
PHP:
<?php
session_start();
/* AUTOMATED VARIABLES */
$url = md5(uniqid(rand(), true));
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$upload_dir = "images/external/doodles/";
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
echo $success ? $file : 'Unable to save the file.';
require_once 'php/connect.php';
try
{
$stmt = $pdo->prepare("INSERT INTO posts (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUE (:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
$stmt->bindParam(":unique_user_id",$unique_user_id);
$stmt->bindParam(":unique_post_id",$unique_post_id);
$stmt->bindParam(":nature",$nature);
$stmt->bindParam(":image_url",$imageUrl);
$stmt->bindParam(":timestamp",$timestamp);
if($stmt->execute())
{
echo "File in database";
}
else
{
echo "Not in database";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
?>
Move $upload_dir at the top, as you are calling it before you initialize it.
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';

Multiple files in to folder

Hello I have a view file and controller, what makes multiple inputs where I can upload files in to folder, but its uploading only one file in to folder. I know what is problem, but I dont know how to fix this or how to do this.
My Controller:
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data['files'];
//print_r($this->data['files']); die;
if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) { // checks for the errors and size of the uploaded file
echo "Failide maht kokku ei tohi olla üle 5MB";
return false;
}
$filename = basename($uploadData['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
return false;
}
echo "Sa sisestasid faili(d): $filename";
}
}
My View file:
<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
?>
<div class="input_fields_wrap">
<label for="uploadFilefiles"></label>
<input type="file" name="data[files]" id="uploadFilefiles">
</div>
<button type="button" class="add_field_button">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php
echo $this->Html->script('addFile');
And this script what Im using in View :
$(document).ready(function() {
var max_fields = 3;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append("<div><input type='file' name='data[files]' id='uploadFilefiles'/><a href='#' class='remove_field'>Kustuta</a></div>");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
I think that, the problem is in input names. If Im doing more inputs, then the inputs names are same, and thanks to this its uploading only one file in to webroot/files folder, but I want these all.
Can anybody help me or give me some tips.
Thanks !
Here is someone with almost exactly the same issue as you have:
Create multiple Upload File dynamically
Try doing the same. I haven't programmed PHP for quite some time, but I guess you should replace data[files] to just data[], so it creates a new array item for each field. Now you are giving each field the same name.
Then you can loop over them in your controller by using:
foreach($_FILES['data'] as $file){
//do stuff with $file
}
EDIT 2:
As you are saying, you want to upload the files (not to a db). So I guess this should work:
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data;
foreach($uploadData as $file){
if ( $file['size'] == 0 || $file['error'] !== 0) { // checks for the errors and size of the uploaded file
echo "Failide maht kokku ei tohi olla üle 5MB";
return false;
}
$filename = basename($file['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($file['tmp_name'], $file)) {
return false;
}
echo "Sa sisestasid faili(d): $filename";
}
}
}
Try this function:
function multi_upload($file_id, $folder="", $types="") {
$all_types = explode(",",strtolower($types));
foreach($_FILES[$file_id]['tmp_name'] as $key => $tmp_name ){
if(!$_FILES[$file_id]['name'][$key]){
$return[$key]= array('','No file specified');
continue;
}
$file_title = $_FILES[$file_id]['name'][$key];
$ext_arr = pathinfo($file_title, PATHINFO_EXTENSION);
$ext = strtolower($ext_arr); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,5);
$file_name = $uniqer . '_' . $file_title;//Get Unique Name
if($types!=''){
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name'][$key]."' is not a valid file."; //Show error if any.
$return[$key]= array('',$result);
continue;
}
}
//Where the file must be uploaded to
if($folder) $folder .= '/';//Add a '/' at the end of the folder
$uploadfile = $folder . $file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'][$key], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name'][$key]."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
}
else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
}
else {
#chmod($uploadfile,0777);//Make it universally writable.
}
}
$return[$key]=array($file_name,$result);
}
return $return;
}
html: <input type="file" name="data_file[]" id="uploadFilefiles">
Call by multi_upload("data_file","upload_to_folder","pdf,jpg,txt,bmp")

Categories