php javascript download .gz file ajax - javascript

In my project I am using Symfony 3 + Filesaver.js and I need to download a .gz file. I do ajax request to my server with the following code:
function requestAjax(json_data) {
var request = $.ajax({
url: '/ajax'
, method: 'post'
, data: json_data
});
return request;
}
var json_text = {'type': 'download_file'};
var request = requestAjax(json_text);
request.done(function (response) {
var blob = new Blob(
[response], {
type: "text/plain;charset=" + document.characterSet});
saveAs(blob, 'filename.gz');
});
On php side I do the following:
$myfile = '/opt/myfile.gz';
$fp = fopen($myfile, "rb");
$response = base64_encode(fread($fp, filesize($myfile)));
fclose($fp);
return new Response($response);
But when I try to open my downloaded file, I get an error that the file is broken and cannot be read (still I can read it on my server and I know that the file is ok). So the question is how to download a .gz file with an ajax call in php + javascript. Thank you.

Related

Uncaught TypeError: Illegal invocation when trying to upload file via ajax? [duplicate]

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.
This is my HTML part:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
and this is my JS jquery script:
$("#upload").on("click", function() {
var file_data = $("#sortpicture").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
alert(form_data);
$.ajax({
url: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".
When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?
Can someone help my finding out whats wrong?
Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <-- )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.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){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
Use pure js
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>

I cant generate pdf with fpdf and ajax

Excuse my bad English.
I have a problem, I try to generate a PDF file with the fpdf library in a php (controller) passing before by an AJAX (jscript), but it does not generate the pdf but it generates this
PNG
IHDRd'©ñ :IDATxíAÇßFÊÆ
(l£Mb1ö`á\6ÓÆí!°gÉ-Ö$\Ârçl4öÁø0"¶7Y#´'BwQÌ
áY¬Äe1rÍ¡µ­ÞªêW¯ª«»§·ÿcõôT½÷êUõëWÕÕ³s³Íááa|ðjí9§ãÖ4îß¿_µ ¨\¸p¡jf¹¹¹ôÇÓDô""zóø
áÕªM#¥£Ç~9<<üÓÖnµ¦TÂÒSòù`q19FÀty-Wb-®ÂÛbêÙ="iî1c-c.5JTÝY¹Qj
ø$ÃúìRTQÕ±bÅ#5kdë(ãûÅÅg-"Ì=rÒîÕ}Ë´+éÁt½¼ÒÑÆZ9iæÅÈpýúõv»MqÀú
ѯ¾ÿé¤j«*!#å~7®ohA÷¾º³#¼ða.l-+M½MÝÈ°vãäöë4ú³æƤD~:¯LÓZä8áûÙhFr>+ú(JXËf^°,ÃÒ2F6ùÉ+fÅ)¡Ö¤1Æ'uÖX¿XÕN1ú*«øZ`
+!^Ãzã7L aüMÇG¹q¿]~)\õ+I&%0È9£UdyB|e¡£¬a½¥ Ìäú'¿6¾­¨¹£ ¬a¥ÉaötOþ¸lBFɶ¬S?I­<4ób+o׬+DÊAfõhUÄev¨ò¼É·ÉGö¬Z9iêÅhVVz¼f]!ɱ±þ­U"×åñ¤7ÞvRÅieØÏá·^g-f^ð°5¬2ÓL©Âr⨧ xJxB 4*TÅ4ób5¬B2¬2¯±^Ï'¦^&°æ³ª
ÈAa'RøÅQ#m#ÀÔ,#m#ÀÔ,#m#ÀÔ,#m#ÀÔ,#m#ÀÔX+¢ôéóJ1æcíÁeúIfÊ5l¶É/v}xZùü<}~)ÙFéºé
GãI¨Ic£ ®:å¥fXåG+W¥ÆlK¿-èÅÒg²j¥IznåRÄ¢%»êÒR%y¢öPöxøGÞvW9m®º¬c#Ëå8T-I¿AÍ°fÄÉ­ÜâÊeÒ¯Ò:FáFE®­¤¤íIk4O·ÇØ.«ÍúU²ÑÖ2
[ªgÀsü81']JKí2jw­%ìÁ°®´îìîþçìÙ3wéÅ ü¯×Òc:z¨hg$[C¡R2>ÜÁüÊè6ëVÉ©q±ÁûÇZ]ÒR=ÆI,ô0^1F ñNä«NJýr"½±Nýëß7ÚQ|¼´ôÃ~ÿMË/6,ÞCGYF¹ZÆ©à1¿VPaVèâTz<çô¡~¦~ÏûðÛ»FDtñâVëÔx¼Õí¾Â0ÂN¡FèªÆ0AD.ÙÉØ-ÆA/ôXÛ»W¢PÕÂsvVWXÕÊaõû$¢µµ¨ÓYØÞÞ¿víãñV{ûï/þ4yæ»7åéÔ($íÇà÷Õ¢%3¤µÝXÆ*ÙÏÒ,ñ^FèCIKõ±aÕ.!T/gy>-S¨Ki©N­ÃO®=¹þÌ×Wã÷úý÷£h~4z!>3ìÞ¸1iµÎF¿Á!(2I
ý/?®F÷ÚkDÔé<¹Wt:£Ñ&ýáðÖw°N2¥ÝTHð_ÃoM§ûQ4ßnKïv%¢Á`t¥u'¯u` !Z2ñXW£{7oÞ¢£ôjsó¿Îv¯·3,/?½´Ô¢£å-gÀJ§WÉ£n÷_ãñt4ú²ß#D½Þ"mn~raïv#[
Ç'`)éÕx<M¾£h~uõ<õûïç´o%ûu'!Åüjì§Ô[xiùõ§ÝE<ÿv¸wĻתm+y¬-bòø¬¬Õ+":{öñ*~§µZ§¶¶|sûCoãV^˨v×LC(m5*kÛaèÛÖõQW¹Q¯v9?%¼Ýkß¼EGëDEóÉ·­Ö©ä Óúýýþû£Ñåü[ÒnUv]髲`1àí'Nº²jåÌÒðöl¬¢ï÷ÃìÝ4½í~ö0ÝÇqc­ÅTÔÛ¥û'½C«YþqêwI-ïqhÅ9`ÅéÕÒRkyùéøL¤VWÏß¼ùEð-+Ç_,0vq¸óÛF]tÜûë/åzHØ®nµGâ%k+þwŨËolHòw«½ccµi¬µÿóþ´7&«]ÞãÐ[ÀºÒº³zó­­-$'/^<U¾×[ìt¶Ñ¨ýÒߦ/ø¨ 7"9}䤫4ÉéA&©åasúVÌGyå#×ÊcýƱ5]ÊÌ?å+W?;¡Á8ÊCi ãPÇ-`
£8½7.褧D§½Þ»/wûþf²½ÿoÌ·CáaÄo­·t¦V~í*ýîRVê/??K.0BǡâûÖÑèc:^Å$ñ+¾¥|oq·rnqðk¤µ
Xvf1ÊI'ÕéË© ֵת®÷y?ÂÕ
öósAM
/aê8dXñ¯20éxÃpø°×{÷oþØɸt/J_ôi¹>¬ãH
èC¿Ï%;iØc,£Ì¬>d`úB+ú-7}Æi>®el;sƨ]Çê­Ç7£KJöè÷BÇ¡éËÏWZwÚíßÑ`pQXýþáð!ýlòítzÐnßNºÝ=µôso[AÓp(1«G·äågéO¯Z­ÇÚ¼éÛSñÓÁ`ãjtÏËlÐ Vv#QÀbV¯b8¥,º'¬®¢ùét0Øð²4u¯×ªÝ(`ÅéUòV³NVJ¯¾Å¯8ü°¬$½J¶¶ëdíMì5íõÞu0°¬øWbÚísLìå#WòòoqÈ"çÓBûé*ͤÓ_V,̨ʨ¼QÆÞVYûɬÄKuaïöææ'tügEln^^`v½Qͯ­E$KÓ3²üü¶YæÑ÷ßÚ
í±ìúqcléM&VWÿ1ôû?HÞ14ríÚùáðÉä˯ÆïI¶87+{¬Û ZiÉBQéZÆ3V(º$í´Bh'o¤øyC²ÍZKØËV]ƶj¤¿óÒÂ|CÞñn©b°íAàÖ½Ûãñ Ò«/§Ó"ò«Õ:Õí>Ûëí£ÑKÖ_qÐ;F9HdädÕJÎ('öHPÞ#ýfmp([{CEJ´[ûT¯bl=Ö²¶Ý¯%ökÉ\×dz??ûÁ¬áð Ò+"zåsÃáÓéAü»}<íö¹áðáööþhôñSK¥÷s0ÝÊeômÄjS&m¡¤S#¢« Úå}*¬Å+cl»®Âc
³]«a¼vNöäg.` W¯(æ77/O&$ûhuõ|¯·3oÿh+¦DnäB1Ú#¹q«¡ì×SÐ%7×îݧ4Ç ùHpˤur9ÏKʳïàÝ[­3D´·÷?¡,a´"¢ÝÝGÂ1AîÕé·,&¿ãËä1;IìaT¬y+WxÃCläl»k#\¼Î5*ÒÆa-/_>ît¶ùg®L§ÛÛû±ü¯Ùé4÷|¦ÏMøDW×eD¥ro¹d=B]:y#T´¶êeaYû]Òf¬*JÐ;~p/?_îu»oÅëîÁY]ýÉ÷^ùUd1TE =ÒNC¡è/?4yîån¿KßÛÛkÄÂÂwBýi)óÎf&wºý÷°îÒt6°ÖûS{ ¡C¶.×5Mîtÿ?U%¨
ÎæëÄ཯ uYOôZÆMÌp£aó=u+\ öSݥ밧ÏïÒ3%QR§·¡4f}¥?ïËz(Rd¿ºräUf$RT»8¡N ˼Òã?{¢lÌ*ìdI´n\Ñ~bERFX¿ôo³v6ëÙ¯](ÇZFâyÒlôüàNö;£9CUܽ3=%Ô³äf¨lqTÊëÅô«.£IÂ<(«SéøÄÍ(_¾Ëè±<Û®_ùç%ËóòÚõDI·º0ÓLCÖ8.­r$CS"'ëμîò²qÖ´N¿ø [íäKØö<zó'>Aú̳°\×hÊ×Åǹ"á4M^ØI²~mW\W(Y9)Ò«R¿m
In¯çkµA9ȧ2ë©÷ù²²ãwefµ(gÛé_Î+TÄx&>PlÎZèe2Ó~7ÖW©Ö3^×ÔçVéõ
ôânÀ|A1ÞÉ^;ãôì[ØvÅ«~63ºxíJ/ëe²lF¶U¤ù¹Ö`DήËÞ軳"ùà¼NX¸0f
×iiqÚQ¿Ew#cAÀÔ,#m#ÀÔ,#m#ÀÔ,#m#ÀÔ,#m#ÀÔ,#m#ÀÔ,#m#ÀÔ'?/ó7W¡ óÚk¯½óÎ;ÉÇÇÖ믿^= åqõöÛoÏÍÍUk
ð<ΰ­³ÏéÃÃÃôçëׯWe
ðÌ)ëöíÛU<ØÖ¨
ÿ/æ7JãpTÙIEND®B`
Here my code
The index calling ajax
index.html
$(document).ready( function()
{
//RESET MODAL CONTENT
resetModal("#myModal");
$("#btn_pdf").click(function(event) {
pdf_requerimiento("usuario", "tipo_maquina", "patente", "codigo_codelco", "hr_inicio", "hr_termino", "fecha", "hr_solicitud", "hr_operador", "hr_gps", "rendimiento_gps", "rendimiento_operador", "rendimiento_maquina", "rendimiento_usuario");
event.preventDefault();
});
});
The Ajax
function pdf_requerimiento(usuario, tipo_maquina, patente, codigo_codelco, hr_inicio, hr_termino, fecha, hr_solicitud, hr_operador, hr_gps, rendimiento_gps, rendimiento_operador, rendimiento_maquina, rendimiento_usuario) {
form = new FormData();
form.append("action", "pdf_requerimiento");
form.append("usuario", usuario);
form.append("tipo_maquina", tipo_maquina);
form.append("patente", patente);
form.append("codigo_codelco", codigo_codelco);
**...**
$.ajax ({
data : form
cache : false,
type : "post",
url : "pages/pdf/controller.pdf.php",
processData : false,
contentType : false,
success : function(data)
{
/*window.open(
'data:application/pdf,'+encodeURIComponent(data)
);*/
},
error : function(data){ alert('Error');
}
});
}
The controller
function requerimiento(){
//Variables
$usuario = $_REQUEST["usuario"];
$maquina = $_REQUEST["tipo_maquina"];
**...**
$pdf = new PDF('P','mm','A4');
$pdf->AddPage();
$pdf->SetFont('Helvetica','B',16);
$pdf->Cell(190,10,'Detalle del Requerimiento','B',2);
$pdf->Output('I','requerimiento_pdf.pdf');
/*
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="requerimiento_pdf.pdf');
*/
}
In php
header("Content-type:application/pdf");
and after
$pdf->Output('I','requerimiento_pdf.pdf');
First you have to set header. And only after that output document.

How do I upload a (.OBJ) Blob file to the server using PHP and jQuery?

I have been trying to upload a file from my webpage to a folder on the server using jQuery and PHP.
Here is my JavaScript code for generating the file to send and then using a POST request to send the file to my PHP script so that it can then handle the file and save it to a particular folder.
//Generate file to send to server
var formData = new FormData();
var characterBlob = new Blob([result], {type: "octet/stream"});
formData.append('Character', characterBlob);
//Communicate with the server
$.ajax({
url: "ExecuteMaya.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formData, // 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);
}
});
Here is my PHP script to handle the sent file and save it in a specified folder.
<?php
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "/Applications/AMPPS/www/webGL/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>";
?>
When I try to send the file from my webpage nothing appears in the 'Upload' folder that I am trying to save the file to.
Could someone please tell me why a file is not saved in the 'Upload' folder? I am eventually looking to open this file in a Maya application on the server and run some Python code. Would I even need to save the file on the server before opening it in Maya? Or could I open Maya with the file straight away?
Try use my code and tell me if it works. This should work if you adapt it to your filenames and input, and other elements ids, it's tested by me:
$('#upload').on('click', function(e) {
$('#message').fadeOut();
e.preventDefault();
if ($('#file')[0].files.length == 0) {
alert('Choose a file!');
} else {
var file_data = $('#file').prop('files')[0]; //file object details
var form_data = new FormData($('#form')[0]);
form_data.append('file', file_data);
var unique_identifier = $('#unique_identifier').val();
$.ajax({
url: 'upload.php',
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) {
$('#message').html(php_script_response).fadeIn();
//alert(php_script_response); // display response from the PHP script, if any
}
});
}
});
<form id='form' action='' method='post' enctype='multipart/form-data'>
<input type='hidden' name='unique_identifier' id='unique_identifier' placeholder='unique identfier' value="<?php echo rand(1000000, 9999999); ?>">
<input type='file' name='file' id='file' />
<a id='upload'>Upload</a>
</form>
And the PHP script I made:
$unique_identifier = (isset($_POST['unique_identifier']))?trim($_POST['unique_identifier']):'';
$upload_directory = 'upload/' . $unique_identifier . '/';
if (!file_exists($upload_directory)) {
mkdir ($upload_directory, 0777);
}
$original_filename = basename($_FILES['file']['name']);
$destination = $upload_directory . $original_filename;
move_uploaded_file($_FILES['file']['tmp_name'], $destination)
Also, I recomend you to do some PHP validation.
It seems you are not appending the file to uploaded to the form data, May be you need something like this.
var elem = $(this).val() // lets say this is the element where you uploaded the photo
var formData = new FormData();
formData.append('file', elem[0].files[0]);
$.ajax({
url: "ExecuteMaya.php",
type: "POST",
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false,
success: function(result){
// your code executed successfully
}

Calling PHP function with ajax to read file

I am taking file input from input type file and calling a javascript function on onchange event like below:
<input type="file" onchange="readTheFile(this)">
The javascript function is calling a php file containing another PHP function. The javascrit function is:
function readTheFile(file){
$.ajax(
{
url: 'readFile.php',
type: 'GET',
data: 'fileLoc= '+file,
success: function(output)
{
document.getElementById("content").innerHTML = output ;
}
}
);
}
</script>
I am always getting the error:
Warning: fopen( [object HTMLInputElement]) [function.fopen]: failed to open stream: No such file or directory in D:\xampp\htdocs\sha\readFile.php on line 3
Unable to open file!
content of readFile.php is:
<?php
function readFiles($fileLoc){
$file = fopen($fileLoc, "r") or exit("Unable to open file!");
while(!feof($file)) {
echo fgets($file);
}
fclose($file);
}
if(isset($_GET['fileLoc'])){
echo readFiles($_GET['fileLoc']);
}
?>
I suggest the FILE API method (moderns browsers only)
See http://www.html5rocks.com/en/tutorials/file/dndfiles/
Example:
<input type="file" id="files" />
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
alert(e.target.result);
};
})(f);
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
Live example here
First move the file into the directory, then your rest function will work.
Here is a jquery plugin to upload file through ajax : jQuery Form Plugin
This plugin send you the parameter of $_FILES to your php file, then first move the file to your directory then use fopen() to read and display content.
It looks like you are making a malformed request. According to the documentation, it says the data option is appended directly onto the url for GET requests. I dont think this is likely because you are hitting the correct php script.
https://api.jquery.com/jQuery.ajax/
Try changing to
function readTheFile(file){
$.ajax(
{
url: 'readFile.php',
type: 'GET',
data: { fileLoc: file },
success: function(output)
{
document.getElementById("content").innerHTML = output ;
}
}
);
}
Also, I dont see where you are pulling the $fileLoc variable from the $_GET array. It might simply be excluded from your code.

using html5 for file upload with ajax and jquery

So i am trying to upload an image along with form data to server. I'm using FileReader API to convert image to data and upload to server. I'm following the code similar to HTML5 uploader using AJAX Jquery.
The data is converted in jquery, but nothing is being sent to server and there is no error generated.
$('#formupload').on('submit', function(e){
e.preventDefault();
var hasError = false;
var file = document.getElementById('file').files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = shipOff;
function shipOff(event) {
result = new Image();
result.src = event.target.result;
var fileName = document.getElementById('file').files[0].name;
$.post('test.php', { data: result, name: fileName });
}
PHP Code
<?php
$data = $_POST['data'];
$fileName = $_POST['name'];
echo $fileName;
$fp = fopen('/uploads/'.$fileName,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $fileName );
echo json_encode($returnData);
?>
Is the problem due to large image file or FileReader API?
I'm not sure if file upload works with filereaders, but there is a different way to make it work:
var formData = new FormData($(".file_upload_form")[0]);
$.ajax({
url: "upload_file.php", // server script to process data (POST !!!)
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // check if upload property exists
// for handling the progress of the upload
myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
}
return myXhr;
},
success: function(result) {
console.log($.ajaxSettings.xhr().upload);
alert(result);
},
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: "application/octet-stream", // Helps recognize data as bytes
processData: false
});
function progressHandlingFunction(e) {
if (e.lengthComputable) {
$("#progress").text(e.loaded + " / " + e.total);
}
}
This way you send the data to the PHP file and you can use $_FILES to process it. Unfortunately, this does not work in IE as far as I know. There might be plugins available that make this possible in IE, but I don't know any of them.

Categories

Resources