Please help me reading an excel file upload attached. When I attach an XLS format, my PHPExcel reader is not working. Do you think where am I missing?
HTML
<form role="form" id="myForm" class="add_customer_form" enctype="multipart/form-data">
<label for="fileUpload">Upload File *</label>
<input type="file" id="files" name="file[]" class="form-control"
accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, text/plain, application/vnd.ms-excel"
multiple required>
</form>
AJAX
//USAGE: $("#form").serializefiles();
(function($) {
$.fn.serializefiles = function() {
var obj = $(this);
/* ADD FILE TO PARAM AJAX */
var formData = new FormData();
$.each($(obj).find("input[type='file']"), function(i, tag) {
$.each($(tag)[0].files, function(i, file) {
formData.append(tag.name, file);
});
});
var params = $(obj).serializeArray();
$.each(params, function (i, val) {
formData.append(val.name, val.value);
});
return formData;
};
})(jQuery);
$.ajax({
url: base_url+'customer/customer_add',
type: 'POST',
data: values,
cache: false,
contentType: false,
processData: false,
success: function(data){
console.log(data);
}
});
PHP
foreach($_FILES["file"]['name'] as $file => $fname) {
$file_path = $_FILES["file"]["tmp_name"][$file];
$extension = pathinfo($fname);
if($extension['extension'] == 'xls') {
$objReader = PHPExcel_IOFactory::createReader('Excel5');
}
else {
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
}
$inputFileType = PHPExcel_IOFactory::identify($file_path);
$objPHPExcel = $objReader->load($file_path);
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
print_r($cell_collection); die();
}
DISPLAY ERROR
Don't trust the file extension.... that xls file is not a native Excel BIFF-format file, no matter what extension it might claim. It's quite common to find .xls used as an extension for csv files, or files containing html markup.
Use the IO Factory's identify() method to tell you what reader to use; or just simply use the IO Factory load() method to select the correct reader and load the file for you.
Related
I have a simple form so you can upload images. I store the uploaded images' properties in a array but I want to post this array to a PHP file using ajax. If I try to get the uploaded image: $_FILES['image1'], it returns an empty array. Any idea what I am doing wrong?
PS: It is important to store the images' properties in a array and pass it to a FormData.
var foo = []; var input = document.getElementById('input');
document.getElementById('add').addEventListener('click', () => {
foo.push(input.files[0]);
});
document.getElementById('check').addEventListener('click', () => {
console.log(foo);
});
document.getElementById('upload').addEventListener('click', () => {
var fd = new FormData();
for (let i = 0; i < foo.length; i++) {
fd.append('image'+i, foo[i]);
}
$.ajax({
enctype: "multipart/form-data",
type: "POST",
url: "path/to/php.file",
data: fd,
dataType: 'json',
contentType: false,
processData: false,
success: function(data) { console.log(data); },
error: function (err) { console.log(err); }
});
});
<button id="add">ADD</button>
<button id="check">CHECK</button>
<button id="upload">UPLOAD</button>
<br><br>
<input type="file" id="input" placeholder="UPLOAD IMAGE">
And the PHP file:
<?php
$arr = array();
array_push($arr, $_FILES);
die(json_encode($arr));
?>
Or you need to check php.ini and check if the size of all the images you add exceeds "upload_max_filesize"
I executed the code with two files. It seems that you can print the files successfully with the following code (PHP file)
print_r($_FILES['image0']);
print_r($_FILES['image1']);
I used jquery 3.5.1, for the ajax call.
I hope it helps.
I'm using javascript to get the filepath but it returns C:\fakepat\ fileName, then I replace the fakepath to get the filename only. Then ajax to php. And execute this line:
copy("filename", $targetPath);
It returns this error no directory or file.
PHP is executed on server-side, therefor it has no access to your client-side file.
To transmit the file from client to server using ajax I recommend wrapping a form around your upload-button. After submitting the XHR you can access the file in PHP via the $_FILES variable and move it where ever you want:
HTML
<form>
<input type="file" id="upload" onchange="javascript:uploadFile()" />
</form>
JS
function uploadFile() {
var formData = new FormData(); // using XMLHttpRequest2
var fileInput = document.getElementById('upload');
var file = fileInput.files[0];
formData.append("uploadfile", file);
request.send(formData);
}
PHP
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['uploadfile']['name']);
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $uploadfile)) {
// upload succeeded
} else {
// upload failed
}
in ajax you can write this
var form_data = new FormData();
var file_data1 = $('#file').prop('files')[0];
form_data.append('file', file_data1);
$.ajax({
url: 'assets/addEdi.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (php_script_response) {
$('#res').html(php_script_response);
}
});
#Toltis Because of the fakepath, you should upload via javascript.
This it the html:
<input type="file" id="file" onchange="upload(event)" />
<img src="" id="img" />
<textbox id="hidden_box" name="hidden_box" style="visibility: hidden;"></textbox>
Then the Js:
function upload(e) {
var input_file = document.getElementById('file');
var hidden = document.getElementById('hidden_box');
var fr = new FileReader();
fr.readAsDataURL(input_file.files[0]);
fr.onloadend = function(e) {
var img_tag = document.getElementById('img');
dataUrl = e.target.result;
img_tag = dataUrl
hidden.innerHTML = dataUrl
}
}
Then you can target the contents of the hidden box in php. Break it on the (,) and then decode the remaining string - base64_decode - and then save it to a file.
The real file name, you already know how to get it.
I want to uploade a file and send additional data (an array) to the php script.
Here is the HTML and the Javascript Code:
<input type="file" name="fileinput" id="fileinput">
<button class="btn btn-primary" id="btnupload">upload</button>
<script>
$('#btnupload').click(function(){
var formData = new FormData();
formData.append("MacsToChangeImage", selectedMACs.toString()); //selectedMACs is the array which i want to send
formData.append("userfile", $('#fileinput').files[0]);
$.ajax({
url: "ChangeImagesFunction.php",
type:'POST',
data: formData,
processData: false,
cententType: false,
success: function(data)
{
alert('success' + data);
},
error:function(response){
alert(JSON.stringify(response));
}
});
});
</script>
And here ist the PHP Code:
if(!empty($_FILES)) {
$target_dir = "img/epd_uploads/";
$temporaryFile = $_FILES['userfile']['tmp_name'];
$targetFile = $target_dir . $_FILES['userfile']['name'];
if(!move_uploaded_file($temporaryFile,$targetFile)) {
echo "Error occurred while uploading the file to server!";
}else{
if (isset($_POST['MacsToChangeImage'])){
//Name of the Uploaded File
$ChangeImageToPHP = $_FILES['userfile']['name'];
//Get the Array
$MacsToChangeImageStr = $_POST['MacsToChangeImage'];
$MacsToChangeImagePHP = explode(",",$MacsToChangeImageStr);
}
}
}
I think the HTML and Javascript part is fine so far. But i am uncertain how to handle the PHP part. What am i doing worng/missing?
Are there other ways to achieve what im plannig to do?
Thank you in advance
I have the following HTML code:
<form action="mail/filesend.php" method="POST" accept-charset="utf-8" enctype="multipart/form-data" validate>
<div class="input-wrpr">
<input type="file" name="files[]">
</div>
<button type="submit">
Send File
</button>
</form>
And then the following file upload code in jQuery:
$(function () {
let files = null;
$('input[type="file"]').on('change' , (e) => {
files = e.target.files;
});
$('form').submit(function(e){
e.stopPropagation();
e.preventDefault();
let data = new FormData();
// files = $('input[type="file"]')[0].files;
$.each(files, function(key, value){
data.append(key, value);
});
console.log(data.getAll('0'));
// console.log(data);
$.ajax({
type: $(this).attr('method'),
url : $(this).attr('action'),
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
data : data
}).done(function(data){
// console.log(data);
if (! data.success) {
// console.log(data.errors);
/*for(let er in data.errors) {
console.log(data.errors[er])
}*/
console.log(data);
} else {
/* else condition fires if form submission is successful ! */
console.log(data.file);
}
}).fail(function(data){
console.log(data);
});
});
});
And the following PHP code for testing :
<?php
// You need to add server side validation and better error handling here
$data = array();
if(isset($_FILES['files'])) {
$data = array('file' => 'I a in if');
}
else {
$data = array('file' => 'I am in else');
}
echo json_encode($data);
?>
Now when i check my console i see that the PHP if condition is not passing , that is it is unable to detect:
isset($_POST['files'])
Why is this happening ? I have tried using isset($_FILES['files']), also I have tried renaming my html file input field to just files instead of files[] , but this does't seem to work , What am I doing wrong ?
I was following the tutorial HERE. But somehow the example I have created just does't work.
Try to print_r($_FILES) and check if it shows an array of file,
If it does, use the same key in $_FILES['same_key_here'] and it supposed to work,
Let me know if it doesn't
If you want to send files, do something like this.
This may help you.
var fileInput = $("#upload_img")[0]; // id of your file
var formData = new FormData();
formData.append("image_file",fileInput.files[0]); //'xmlfile' will be your key
Check in your php code like,
echo $_POST['image_file'];
I want to uplod multiple files through ajax but I can't figure out how I can grab the files in PHP. Can anyone help me? Thank you!
Here is the code:
HTML:
<form enctype="multipart/form-data" method="POST">
<input type="file" id="file" multiple="multiple" name="file"/>
</form>
<div id="info"></div>
<div id="preview"></div>
JavaScript:
$(document).ready(function(){
$("#file").change(function(){
var src=$("#file").val();
if(src!="")
{
formdata= new FormData(); // initialize formdata
var numfiles=this.files.length; // number of files
var i, file, progress, size;
for(i=0;i<numfiles;i++)
{
file = this.files[i];
size = this.files[i].size;
name = this.files[i].name;
if (!!file.type.match(/image.*/)) // Verify image file or not
{
if((Math.round(size))<=(1024*1024)) //Limited size 1 MB
{
var reader = new FileReader(); // initialize filereader
reader.readAsDataURL(file); // read image file to display before upload
$("#preview").show();
$('#preview').html("");
reader.onloadend = function(e){
var image = $('<img>').attr('src',e.target.result);
$(image).appendTo('#preview');
};
formdata.append("file[]", file); // adding file to formdata
console.log(formdata);
if(i==(numfiles-1))
{
$("#info").html("wait a moment to complete upload");
$.ajax({
url: _url + "?module=ProductManagement&action=multiplePhotoUpload",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res){
if(res!="0")
$("#info").html("Successfully Uploaded");
else
$("#info").html("Error in upload. Retry");
}
});
}
}
else
{
$("#info").html(name+"Size limit exceeded");
$("#preview").hide();
return;
}
}
else
{
$("#info").html(name+"Not image file");
$("#preview").hide();
return;
}
}
}
else
{
$("#info").html("Select an image file");
$("#preview").hide();
return;
}
return false;
});
});
And in PHP I get $_POST and $_FILES as an empty array;
Only if I do file_get_contents("php://input"); I get something like
-----------------------------89254151319921744961145854436
Content-Disposition: form-data; name="file[]"; filename="dasha.png"
Content-Type: image/png
PNG
���
IHDR��Ò��¾���gǺ¨��� pHYs��������tIMEÞ/§ýZ�� �IDATxÚìw`EÆgv¯¥B-4 ½Ò»tBU©)"¶+*"( E¥J7ôÞ;Ò¤W©¡&puwçûce³WR¸ èóûrw»³ï}fö
But I can't figure out how to proceed from here.
I am using Jquery 1.3.2 maybe this is the problem?
Thank you!
Sorry about the answer, but I can't add a comment yet.
I would recommend not checking the file type in javascript, it is easily bypassed. I prefer to scrutinise the file in PHP before allowing it to be uploaded to a server.
e.g.
This answer taken from another question (uploaded file type check by PHP), gives you an idea:
https://stackoverflow.com/a/6755263/1720515
<?php
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['fupload']['tmp_name']);
$error = !in_array($detectedType, $allowedTypes);
?>
You can read the documentation on the exif_imagetype() function here.
Could you post your PHP code please? And I will update my answer if I have anything to add.
UPDATE:
NOTE: The 'multiple' attribute (multiple="multiple") cannot be used with an <input type='file' /> field. Multiple <input type='file' /> fields will have to be used in the form, naming each field the same with [] added to the end to make sure that the contents of each field are added to an array, and do not overwrite each other when the form is posted.
e.g.
<form enctype="multipart/form-data" method="POST">
<input type="file" id="file_0" name="img_file[]" />
<input type="file" id="file_1" name="img_file[]" />
<input type="file" id="file_2" name="img_file[]" />
</form>
When the form is submitted, the contents of any <input type='file' /> fields will be added to the PHP $_FILES array. The files can then be referenced using $_FILES['img_file'][*parameter*][*i*], where 'i' is key associated with the file input and 'paramter' is one of a number of parameters associated with each element of the $_FILES array:
e.g.
$_FILES['img_file']['tmp_name'][0] - when the form is submitted a temporary file is created on the server, this element contains the 'tmp_name' that is generated for the file.
$_FILES['img_file']['name'][0] - contains the file name including the file extension.
$_FILES['img_file']['size'][0] - contains the file size.
$_FILES['img_file']['tmp_name'][0] can be used to preview the files before it is permanently uploaded to the server (looking at your code, this is a feature you want to include)
The file must then be moved to its permanent location on the server using PHP's move_uploaded_file() function.
Here is some example code:
<?php
if (!empty($_FILES)) {
foreach ($_FILES['img_file']['tmp_name'] as $file_key => $file_val) {
/*
...perform checks on file here
e.g. Check file size is within your desired limits,
Check file type is an image before proceeding, etc.
*/
$permanent_filename = $_FILES['img_file']['name'][$file_key];
if (#move_uploaded_file($file_val, 'upload_dir/' . $permanent_filename)) {
// Successful upload
} else {
// Catch any errors
}
}
}
?>
Here are some links that may help with your understanding:
http://www.w3schools.com/php/php_file_upload.asp
http://php.net/manual/en/features.file-upload.multiple.php
http://www.sitepoint.com/handle-file-uploads-php/
Plus, some extra reading concerning the theory around securing file upload vulnerabilities:
http://en.wikibooks.org/wiki/Web_Application_Security_Guide/File_upload_vulnerabilities
You can use ajax form upload plugin
That's what i have found couple of days ago and implemented it this way
Ref : LINK
You PHP Code can be like this
uploadimage.php
$response = array();
foreach ($_FILES as $file) {
/* Function for moving file to a location and get it's URL */
$response[] = FileUploader::uploadImage($file);
}
echo json_encode($response);
JS Code
options = {
beforeSend: function()
{
// Do some image loading
},
uploadProgress: function(event, position, total, percentComplete)
{
// Do some upload progresss
},
success: function()
{
// After Success
},
complete: function(response)
{
// Stop Loading
},
error: function()
{
}
};
$("#form").ajaxForm(options);
Now you can call any AJAX and submit your form.
You should consider below code
HTML
<input type="file" name="fileUpload" multiple>
AJAX
first of all you have to get all the files which you choose in "input type file" like this.
var file_data = $('input[type="file"]')[0].files;
var form_data = new FormData();
for(var i=0;i<file_data.length;i++)
{
form_data.append(file_data[i]['name'], file_data[i]);
}
then all your data is in formData object now you can send it to server(php) like this.
$.ajax({
url: 'upload.php', //your php action page name
dataType: 'json',
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (result) {
// code you want to execute on success of ajax request
},
error: function (result) {
//code you want to execute on failure of ajax request
}
});
PHP
<?php
foreach($_FILES as $key=>$value)
{
move_uploaded_file($_FILES[$key]['tmp_name'], 'uploads/' .$_FILES[$key]['name']);
}