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.
Related
trying to upload a file without using a form and using $.post to transfer the file
I suppose the problem is on php side, but I'm not sure
<input type='file' id='inpfile'>
$(inpfile).on('change', function(){
var fd = new FormData();
var file = $(inpfile)[0].files[0];
fd.append('file', file);
fd = JSON.stringify(fd);
$.post('pro.php', {fn: 'upload', args: [fd]}, function(data){
console.log(data);
});
});
pro.php
if(isset($_POST['fn'], $_POST['args'])){
$fn = $_POST['fn']; $args = $_POST['args'];
$fn(...$args);
}
function upload($fd){
$fd = json_decode($fd);
$fname = $fd->file;
$destination = 'upload/' . $fname;
move_uploaded_file($fname, $destination);
}
you cannot upload file simply with $.post method and form data when changed to string cannot send file. you need to add contentType:false and processData:false, and remove this code fd = JSON.stringify(fd); Moreover, your jquery does not recognize the change since you have not addressed it properly. it should be $('#inpfile').on('change', function()
instead of just $(inpfile).on('change', function()
you can try this code.
<input type='file' id='inpfile'>
$('#inpfile').on('change', function(){
var fd = new FormData();
var files = $('#inpfile')[0].files;
fd.append('file',files[0]);
$.ajax({
url: 'pro.php',
method: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
//your code.....
}
});
});
and in the PHP server side you check it with files method instead of post method. that is
if(isset($_FILES['file']['fd'])){
your code.......
}
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.
I am sending a file to an external server using ajax and api.I attached a file and then when i clicked on the upload button. It gets the content of the file and then send it to the external server using it's API. The request must be in json otherwise it rejects the data
Below are my code
<form enctype="multipart/form-data" id="form_submit_new_resume" method="POST" action="" onsubmit="return false;">
<input type="file" name="textfile" id="textfile">
<input type="button" onclick="submitform()">
</form>
Below is my javascript file
function submitform(){
var filesSelected = document.getElementById("textfile").files;
if (filesSelected.length > 0)
{ document.getElementById('loading').style.display="block";
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textAreaFileContents = document.getElementById
(
"textAreaFileContents"
);
var fileName = fileToLoad.name;
var base64encode = fileLoadedEvent.target.result;
jQuery.ajax(
{
url : "https://api.resumatorapi.com/v1/applicants",
type: 'POST',
dataType : "json",
contentType : "application/json",
data: '{"apikey":"apikey", "resumetext" : "'+base64encode+'"}',
}
)
}
It successfully upload the file but when i see the file on server then it is showing invalid file.
If i use php's inbuilt function get_file_content then it is showing the correct text but i want to do it through ajax.Is there any other way to get the exact content of a doc file using jquery or javascript?
I'm using pdfmake to create my pdf and while it allows the user to open the pdf directly or download it to their computer, I'm not sure how I would go about generating the pdf and saving it to my server's file system.
From what I understand, there are plenty of security measures not allowing javascript to save data to file(s), so would sending it to my php backend be the only choice ? and how would i go about doing that ?
Thanks !
(untested)
PHP:
<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
echo ($decodedData);
$filename = "test.pdf";
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
JS:
var docDefinition = {
content: 'This is an sample PDF printed with pdfMake'
};
pdfMake.createPdf(docDefinition).getBuffer(function(buffer) {
var blob = new Blob([buffer]);
var reader = new FileReader();
// this function is triggered once a call to readAsDataURL returns
reader.onload = function(event) {
var fd = new FormData();
fd.append('fname', 'test.pdf');
fd.append('data', event.target.result);
$.ajax({
type: 'POST',
url: 'upload.php', // Change to PHP filename
data: fd,
processData: false,
contentType: false
}).done(function(data) {
// print the output from the upload.php script
console.log(data);
});
};
// trigger the read from the reader...
reader.readAsDataURL(blob);
});
Upload and receive code from How can javascript upload a blob?.
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']);
}