I have a php file which takes a zip file and unpacks it then places it at the desired path on my server.
It works great with a typical form that calls on the php file in the action. I am trying to make this work with AJAX but I have tried every piece of code I can find without any luck.
Is there something here I am missing? Surely this can be done?
Form for uploading the zip file,
<div id="response"></div>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" id="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" onClick="uploadZip()" />
</form>
Current JS - I get no errors, the page actually reloads with my current script..
<script>
function uploadZip() {
formdata = new FormData();
if (formdata) {
$('.main-content').html('<img src="LoaderIcon.gif" />');
$.ajax({
url: "assets/upload-plugin.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res){
document.getElementById("response").innerHTML = res;
}
});
}
}
</script>
php script which handles uploading the zip and unzipping it before placing it on the server.
function rmdir_recursive($dir) {
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
rmdir($dir);
}
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
/* PHP current path */
$path = '../plugins/'; // absolute path to the directory where zipper.php is in
$filenoext = basename ($filename, '.zip'); // absolute path to the directory where zipper.php is in (lowercase)
$filenoext = basename ($filenoext, '.ZIP'); // absolute path to the directory where zipper.php is in (when uppercase)
$targetdir = $path . $filenoext; // target directory
$targetzip = $path . $filename; // target zip file
/* create directory if not exists', otherwise overwrite */
/* target directory is same as filename without extension */
if (is_dir($targetdir)) rmdir_recursive ( $targetdir);
mkdir($targetdir, 0777);
/* here it is really happening */
if(move_uploaded_file($source, $targetzip)) {
$zip = new ZipArchive();
$x = $zip->open($targetzip); // open the zip file to extract
if ($x === true) {
$zip->extractTo($targetdir); // place in the directory with same name
$zip->close();
unlink($targetzip);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
This php function works great as long as I do this with the form action. So I am sure my problem exist in the AJAX function.
Thanks for any help you can provide.
formdata = new FormData();
You've created a FormData object but you never put any data into it.
The easiest approach is to specify the form:
formdata = new FormData(document.forms[0]);
You also need to stop the submit button from actually submitting the form so that the JS can do something.
A cleaner approach would be to:
Stop using intrinsic event attributes
Use the submit handler for the form
Get the form from the event
<input type="submit" name="submit" value="Upload" onClick="uploadZip()" />
Becomes:
<input type="submit" name="submit" value="Upload">
function uploadZip() {
formdata = new FormData();
becomes:
function uploadZip(event) {
var formdata = new FormData(this);
// Rest of function
event.preventDefault();
}
and you add:
jQuery("form").on("submit", uploadZip);
Related
For creating a .zip file for checked items with selectbox, i need a response back from the php that leads to the path the .zip file is stored.
This is my ajax call:
// AJAX for Checkbox download
$(document).on('click' , '.cb_down' , function() {
var checkboxes_down = [];
$('.rafcheckbox').each(function() {
if(this.checked) {
checkboxes_down.push($(this).val());
}
});
checkboxes_down = checkboxes_down.toString();
$.ajax({
url:"",
method:"POST",
data:{ checkboxes_down:checkboxes_down },
success:function(response){
window.location = response; // this should lead me to the zip file
}
//.........
My php:
// Multiple download (checkboxes)
if(isset($_POST["checkboxes_down"])) {
// create a tmp folder for the zip file
$tmpfolder = $MainFolderName.'/tmpzip';
if (!is_dir($tmpfolder)) {
mkdir($tmpfolder, 0755, true);
}
$checkboxfiles = explode("," , $_POST["checkboxes_down"]);
$filename = "archive.zip";
$filepath = $tmpfolder."/";
foreach($checkboxfiles as $checkboxfile) {
Zip($checkboxfile, $tmpfolder."/archive.zip"); // Zip is a function that creates the .zip file
}
// header come here
echo $filepath . $filename; // the path to the .zip file
exit;
The .zip file is successful created. I checked it.
The problem is: i do not get the response back from the php script.
So i can not download the .zip file.
What i am doing wrong?
! I changed the echo to 'zip file is created' but even that echo i do not receive as response back
In my page I had only one html file input :
input type="file" name="file" files-model="service.file" id="filo" accept=".zip" />
And I used to get my file to be uploaded in a multi-part file request like this :
var fd = new FormData();
fd.append('file', filo.files[0]);//filo is the id of the input
//and send my http request having fd as a parameter
The problem is that now I have auto generated forms in my page with angular ng-repeat so I can no more get my file using the input ID, how can I do this now ?
Cheers,
It will be a bit tricky with javascript. this library worked for me. see example below.
<a class="btn btn-sm btn-primary"
type="file"
ngf-select="receiveSlectedFiles($file)">
Select Logo
</a>
whenever you select file, you will get it in receiveSlectedFiles($file) function. when user select valid file it will be in $file if not the $file will be null.
example in controller:
var arrayOfFiles = [];
$scope.receiveSlectedFiles = function (file) {
if (file) {
arrayOfFiles.push(file);
}
};
In service, inject Upload and then use below code to upload image:
this.uploadMultiple = function (files) {
var uri = yourApiUrl;
return Upload.upload({
url: uri,
arrayKey: '',
data: {
files: files
}
})
};
in controller, you just need to pass array of files to this service.
We are taking over a site that is using Angular js for a form for data and multi-file upload (up to 4 files).
We are posting to a .php file. I have been able to separate and capture the field data - but can only seem to 'see' one file. If I upload multiple files I 'see' only the last one added to the form.
Can someone please help me to get the files using PHP?
Form HTML (for files):
<ul class="attachments">
<li ng-repeat="attachment in attachments" class="attachment">
{{attachment.name}}
<i class="btn-submit-att-x-hover-off"></i>
</li>
</ul>
<button type="button" class="attachments-button btn btn-default" ngf-select ngf-change="onFileSelect($files)" ngf-multiple="true" ng-if="attachments.length < 4">
<i class="btn-submit-attch"></i>Upload Attachments
</button>
Angular JS Code - for the files as I see:
$scope.attachments = [];
//onFileSelect adds file attachments to the $scope up to the
//configured maximum value.
$scope.onFileSelect = function ($files) {
var MAX_ATTACHMENTS = 4;
for(var i=0; i < $files.length; i++){
if($scope.attachments.length >= MAX_ATTACHMENTS){
break;
}
$scope.attachments.push($files[i]);
}
};
$scope.removeAttachment = function (attachment) {
var index = $scope.attachments.indexOf(attachment);
if (index > -1) {
$scope.attachments.splice(index, 1);
}
};
//POST form data
$scope.upload = Upload.upload({
url: 'forms/pressrelease.html',
method: 'POST',
data: $scope.model,
file: $scope.attachments,
fileFormDataName: "files"
})
.success(function (data, status, headers, config) {
alertSuccess("Your press release has been submitted successfully!");
$scope.showSuccess = true;
}
The only PHP code we've used that has given us anything back - but again - only 1, or the last file name is:
if(isset($_FILES['files'])){
$files = $_FILES['files'];
$sentfilename = $_FILES['files']['name'];
$email_body .= "I see files: $sentfilename<br />";
$tmpsentfile = $_FILES['files']['tmp_name'];
$i=0;
$getfile = $files[0];
$sentfilename = $getfile;
$sentfilesize = $_FILES['files']['size'];
$errormessage = $_FILES['files']['error'];
$email_body .= "I see files: $sentfilename<br />";
}
If anyone one can show us the PHP code we need to use to capture these uploaded files.
Thanks
Create a names array and post the dynamic file names:
var names = []
foreach file:
names.push(files[i].name)
in upload:
method: 'POST',
data: $scope.model,
file: $scope.attachments,
fileFormDataName: names
i have the form and uploading images which works fine i want to process it through ajax or javascript. how can i adjust my code with javascript so it will not refresh the page and will just print a message UPLOADED Successfully. any help will be highly appreciated.
my code is below:
HTML:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="uploadForm" method="post" enctype="multipart/form-data" action='upload.php'>
<input name="file" type="file" size="20" />
<input name="submit" type="submit" value="Upload" />
</form>
</body>
</html>
my JS:
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
error: function()
{
}
});
}));
});
</script>
upload.php:
<?php
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {
//Config Section
//Set file upload path
$path = 'uploads/'; //with trailing slash
//Set max file size in bytes
$max_size = 1000000;
//Set default file extension whitelist
$whitelist_ext = array('jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
//The Validation
// Create an array to hold any output
$out = array('error'=>null);
if (!$file_field) {
$out['error'][] = "Please specify a valid form field name";
}
if (!$path) {
$out['error'][] = "Please specify a valid upload path";
}
if (count($out['error'])>0) {
return $out;
}
//Make sure that there is a file
if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {
// Get filename
$file_info = pathinfo($_FILES[$file_field]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$out['error'][] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
$out['error'][] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$file_field]["size"] > $max_size) {
$out['error'][] = "File is too big";
}
//If $check image is set as true
if ($check_image) {
if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
$out['error'][] = "Uploaded file is not a valid image";
}
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$out['error'][] = "A file with this name already exists";
}
if (count($out['error'])>0) {
//The file has not correctly validated
return $out;
}
if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
//Success
$out['filepath'] = $path;
$out['filename'] = $newname;
return $out;
} else {
$out['error'][] = "Server Error!";
}
} else {
$out['error'][] = "No file uploaded";
return $out;
}
}
?>
<?php
if (isset($_POST['submit'])) {
$file = uploadFile('file', true, true);
if (is_array($file['error'])) {
$message = '';
foreach ($file['error'] as $msg) {
$message .= '<p>'.$msg.'</p>';
}
} else {
$message = "File uploaded successfully";
}
echo $message;
}
?>
i have the form and uploading images which works fine i want to process it through ajax or javascript. how can i adjust my code with javascript so it will not refresh the page and will just print a message UPLOADED Successfully.
I tried alot for my question and atlast i am succeeded. the answer is below:
HTML
<script src="js/jquery.min.js"></script>
<script src="js/ajax-upload.js"></script>
<form id="frmUpload" action="" method="POST" name="default" class="form-horizontal">
<div class="img-upload">
<input type="file" name="file" id="file" class="user-image" required />
<div class="img-preview"></div>
<div class="upload-msg"></div>
</div>
<div class="form-actions">
<input type="submit" name="submit" value="Add Image Or Audio File" class="btn btn-primary">
<input type="reset" name="reset" value="Reset" class="btn">
</div>
</form>
ajax-upload.js
$(document).ready(function (e) {
$("#frmUpload").on('submit',(function(e) {
e.preventDefault();
$(".upload-msg").text('Loading...');
$.ajax({
url: "process.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // 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
{
$(".upload-msg").html(data);
}
});
}
));
// Function to preview image after validation
$("#file").change(function() {
$(".upload-msg").empty();
var file = this.files[0];
var imagefile = file.type;
var imageTypes= ["image/jpeg","image/png","image/jpg","image/gif"];
if(imageTypes.indexOf(imagefile) == -1)
{
$(".upload-msg").html("<span class='msg-error'>Please Select A valid Image File</span><br /><span>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = function(e){
$(".img-preview").html('<img src="' + e.target.result + '" />');
};
reader.readAsDataURL(this.files[0]);
}
});
});
process.php
<?php
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {
//Config Section
//Set file upload path
$path = 'uploads/'; //with trailing slash
//Set max file size in bytes
$max_size = 1000000;
//Set default file extension whitelist
$whitelist_ext = array('jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
//The Validation
// Create an array to hold any output
$out = array('error'=>null);
if (!$file_field) {
$out['error'][] = "Please specify a valid form field name";
}
if (!$path) {
$out['error'][] = "Please specify a valid upload path";
}
if (count($out['error'])>0) {
return $out;
}
//Make sure that there is a file
if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {
// Get filename
$file_info = pathinfo($_FILES[$file_field]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$out['error'][] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
$out['error'][] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$file_field]["size"] > $max_size) {
$out['error'][] = "File is too big";
}
//If $check image is set as true
if ($check_image) {
if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
$out['error'][] = "Uploaded file is not a valid image";
}
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$out['error'][] = "A file with this name already exists";
}
if (count($out['error'])>0) {
//The file has not correctly validated
return $out;
}
if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
//Success
$out['filepath'] = $path;
$out['filename'] = $newname;
return $out;
} else {
$out['error'][] = "Server Error!";
}
} else {
$out['error'][] = "No file uploaded";
return $out;
}
}
?>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_FILES["file"]["type"])){
$file = uploadFile('file', true, true);
if (is_array($file['error'])) {
$message = '';
foreach ($file['error'] as $msg) {
$message .= '<p>'.$msg.'</p>';
}
} else {
$message = "File uploaded successfully";
}
echo $message;
}
?>
Use the success property of $.ajax which is a function, to execute some code after a successful request.
Exemple :
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function() {
//Code on successful request
console.log('UPLOAD Successfully');
},
error: function()
{
}
});
This should good to go assuming you get a proper response from your php,
Too lazy to explain, lol
HTML
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<style>
body {
position: relative;
}
.loader {
position: absolute;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.42);
display: none;
}
.loader.active {
display: block;
}
</style>
</head>
<body>
<div class="loader"></div>
<form id="uploadForm" method="post" enctype="multipart/form-data">
<input name="file" type="file" size="20" />
<input name="submit" type="submit" value="Upload" />
</form>
<div class="notice"></div>
</body>
</html>
EDITED
First make sure there's no error on the console log,
then check everything on console log
<script type="text/javascript">
$(document).ready(function () {
// Capture Form Submit Aaction
$("#uploadForm").on('submit',(function() {
// Show Loader Div when Button is click
$('.loader').addClass('active');
// Add Console Message confirming button is click
console.log('Start Ajax');
// Start Ajax Request
$.ajax({
type: 'POST',
// Place URL upload.php url here
url: 'http://yoursite.com/filesordir/upload.php',
// Never check your PHP data so I leave this lines below,
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
// If ajax response is success
success: function(data) {
// Hide the Loader Div
$('.loader').removeClass('active');
// Inser Ajax response to notice div
$('.notice').html( data );
// Add Console message
console.log('Ajax Success');
}
error: function( errorThrown ) {
// Hide the Loader Div
$('.loader').removeClass('active');
// Inser error message to notice div
$('.notice').html( errorThrown );
// Add Console message
console.log('Ajax Error');
}
});
//Edited this, have double ")".
});
});
</script>
sorry if I am being redundant but I've tried every single example I found here and on google :D
What I am trying to do is on the upload of image, what was typed on inputbox will be send along to the uplodify.php where my insert is. My problem is, name of picture has being saved to the mysql but what was typed on the textfield dont.
Would you guys let me know what is going on?
This is the part of my code
'multi' : true,
'auto' : false,
'onUploadStart' : function(file) {
$("#file_upload").uploadify('settings', 'formData', {'galeria': $('#galeria').val()});
},
<form id="form1" name="form1" action="">
<p>
<input type="file" id="file_upload" name="file_upload" />
<br>
<br>
Galeria<br>
<label>
<input type="text" name="galeria" id="galeria">
uplodify.php
$galeria = $_POST['galeria'];
$regiao = $_POST['regiao'];
if (!empty($_FILES)) {
$img = $_FILES['Filedata']['name'];
$ext = substr($img, -4);
$img = md5($img).date("dmYHis").$ext;
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $img;
$adicionar = mysql_query ("INSERT INTO imagens (foto, galeria, regiao) VALUES('$img','$galeria','$regiao')");
// $fileTypes = str_replace('*.','',$_REQUEST['fileext']);
// $fileTypes = str_replace(';','|',$fileTypes);
// $typesArray = split('\|',$fileTypes);
// $fileParts = pathinfo($_FILES['Filedata']['name']);
// if (in_array($fileParts['extension'],$typesArray)) {
// Uncomment the following line if you want to make the directory if it doesn't exist
// mkdir(str_replace('//','/',$targetPath), 0755, true);
move_uploaded_file($tempFile,$targetFile);
echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);
// } else {
// echo 'Invalid file type.';
// }
}
Try changing your onUploadStart method to extend the uploadify formData property like this:
onUploadStart: function ( file ) {
var $fileUpload = $('#file_upload')
, formData = $fileUpload.uploadify('settings', 'formData')
, newFormData = $.extend({}, formData, { galeria: $('#galeria').val() });
$fileUpload.uploadify('settings', 'formData', newFormData);
}
I finally managed to made it work
This is the code I used
$('#file_upload').attr('file_upload', response).show();
$.post("insert2.php",{name: fileObj.name, galeria: $("#galeria").val(), regiao: $("#regiao").val()}, function(info) {
alert(info); // alert UPLOADED FILE NAME
});
}
});
Now I have a different problem lol it always show right...
Since the code to save the file on dabase is on insert2.php and the code to rename the picture inside the uploadify.php. How can I save the new name on the database instead the name of file I uploaded?
Another question.... is that a way to generate a thumbnail based on those pictures on database?