Ajax & PHP uploading files [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm starting with web programming with javascript and i have a little problem with uploading file.
I find this: http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/
but I have no idea how to use upload.php file in mvc project. What to use as an action of form and where should be plasted this php code?
Can anyone give mi some hints?

you can upload you're file with ajax if you create a controller with php:
<?php
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // Autorized extensions
$max_size = 200 * 1024; // Max file size
$path = 'uploads/'; // Folder where to upload
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if( ! empty($_FILES['image']) )
{
// Get the extension of the file
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
// Test the file format if it's allowed
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'] < $max_size)
{
$path = $path . uniqid(). '.' .$ext;
// Put the file in the folder of uploads
if (move_uploaded_file($_FILES['image']['tmp_name'], $path))
echo $path; // returning the path
else
echo 'uploads/err.gif'; // returning the error message or path or whatever
}
else
echo 'uploads/err.gif';
}
else
echo 'uploads/err.gif';
}
else
echo 'uploads/err.gif';
?>
In you're view, you have to include jQuery.form library and. you create a form, and inside the form you put an image and a button, the form should have the link of you're php file as action, and call this function:
$('#form').ajaxUpload($('#button'),$('#image_preview'));
The definition of ajaxUpload function is this:
jQuery.fn.ajaxUpload = function(Button,Preview)
{
var Frm = $(this); // form
var Btn = Button; // upload button
var Prev = Preview; // preview area
Btn.click(function()
{
// implement with ajaxForm Plugin
Frm.ajaxForm(
{
beforeSend: function()
{
Btn.attr('disabled', 'disabled');
Prev.fadeOut();
},
success: function(Result)
{
Frm.resetForm();
Btn.removeAttr('disabled');
Prev.attr("src",Result).fadeIn();
},
error: function(Result)
{
Btn.removeAttr('disabled');
Prev.attr("src",Result).fadeIn();
}
});
});
};

Related

Image Download Issue with jquery plugin and php stuff

I have created a QR code generating website. QR code is generated through PHP QR code generator library
by using this code
include_once "../phpqrcode/qrlib.php";
$PNG_TEMP_DIR = '../qrcodeImages/';
if (isset($_REQUEST['text'])) {
$content = $_REQUEST['text'];
$filename = $PNG_TEMP_DIR . 'qr' . md5($content) . '.png';
QRcode::png($content, $filename, 10);
echo $image = "<img class='img' src='qrcodeImages/" . basename($filename) . "'/>";
// $image_src = "qrcodeImage/" . basename($filename);
};
with this ajax call i append the QR code in the required div
$.ajax({
url: "code/single_input_to_qrcode.php",
type: "POST",
data: { text: jquery_plain_text },
success: (parms) => {
$("#downloadPart_img img").remove();
$("#downloadPart_img").append(parms);
}
});
and under QR code div I have placed a download button which is used to download the QR code
for downloading purpose I have used JavaScript library "File Saver"
code
var url = $("#downloadPart_img img").attr('src');
if (url == "img/white-qr-code.png") {
$("#error_msg_div").animate({ "top": "20px" });
error_msg = "Please generate a QR code before download";
error_msg_div.html(error_msg);
} else {
var file_name = url.substring(url.lastIndexOf('/') + 1);
url = "localhost/qrCodeGenerator/" + url;
saveAs(url, file_name);
}
But when user hit download button it show failed to download what kind of issue is that. I thinks this is because when the user hit the download button at the same time the file is saving in the folder so file is not available their at that time.
I have search a lot about that but I am fail to get its solution so now I am on this site to find solution so if some one now how to fix this problem so please help me.
Advance thanks
image of website and failed file at left bottom

How can I create a Dynamic DropDownBox in SapUi5? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have one test folder in ProjectExplorer . In that folder i have multiple JSON files. I want to create a DropDownBox which will have all the files name containing in that folder. Also , when i click on any file I want to Display that file in a TextArea . I want to do this in SapUi5. Please Suggest
What I have tried so far
var oText = new sap.ui.commons.Label({
text : "Saved Files"
});
var SavedFiles = new sap.ui.commons.DropdownBox();
var oItem = new sap.ui.core.ListItem();
#!/usr/bin/perl
$basedir = "data"; //folder location
#files = ('*.json');
chdir($basedir);
foreach $file (#files)
{
$ls = `ls $file`;
#ls = split(/\s+/,$ls);
foreach $temp_file (#ls)
{
if (-d $file)
{
$filename = "$file$temp_file";
if (-T $filename)
{
push(#FILES,$filename);
}
}
elsif (-T $temp_file)
{
push(#FILES,$temp_file);
}
}
}
foreach $FILE (#FILES)
{
oItem.setText("filename");
SavedFiles.addItem(oItem);
}
It can be done, but you need to make the directory browsable.
Create a .htaccess file in the directory you need to read, and in that file add the following:
Options +Indexes
Implement the following:
var aFiles = [];
$.ajax({
url : "http://localhost:8010/", // or whatever URL you use
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(json)$/) ) {
aFiles.push(val);
}
});
console.log(aFiles); //aFiles holds an array with all the *.json files
}
});

Trying to upload images without refreshing page with javascript, not working

I am trying to upload images to my server via an html-form without refreshing the page. My problem is the files arent getting uploaded and I cant figure out why.
Javascript code:
function uploadFiles(event) {
var fileSelect = document.getElementById('file');
var files = fileSelect.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image.*')) {
alert("File: " + file.name + " is not an image and will not be uploaded.");
continue;
}
formData.append('images[]', file, file.name);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', '../htdocs/Php/upload_file.php', true);
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
alert('files uploaded');
} else {
alert('An error occurred!');
}
};
xhr.send(formData);
}
HTML code:
<form action="../htdocs/Php/upload_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="images[]" id="file" onchange="uploadFiles()" multiple required />
</form>
PHP code:
$numberOfFiles = count($_FILES['images']['name']);
for($id = 0; $id < $numberOfFiles; $id++)
{
if (!file_exists("../UploadedImages/" . $_FILES["images"]["name"][$id])) {
move_uploaded_file($_FILES["images"]["name"][$id], "../UploadedImages/" . $_FILES["images"]["name"][$id]);
}
}
Looks like your JavaScript is correct, but your PHP needs some attention. I modified your php so that it first check to see if $_FILES were passed. Then where you had some incorrect logic was in your !file_exists() statement and how you move and check the file name.
To check if a file exists, and to move the file you need to use $_FILES['images']['tmp_name']. The 'name' attribute is just the name of the file uploaded, not the physical file uploaded to the browser.
To really test your code, use firebug and look at the console. It should return a line that you can expand and look at what was posted and what was returned.
Here is an example, the following code i gave you returns this:
C:\filepath\binaries\tmp\phpDB53.tmp Was Succesuflly uploaded
C:\filepath\binaries\tmp\phpDB54.tmp Was Succesuflly uploaded
C:\filepath\binaries\tmp\phpDB55.tmp Was Succesuflly uploaded
C:\filepath\binaries\tmp\phpDB56.tmp Was Succesuflly uploaded
NOTE: Double check that the files paths are absolutely correct. When checking firebug console, the php file will also return file errors as well, given that you have php error reporting on.
//Check if files were passed through to your ajax page
if(isset($_FILES)) {
$numberOfFiles = count($_FILES['images']['name']);
for($id = 0; $id < $numberOfFiles; $id++)
{
if (file_exists($_FILES["images"]["tmp_name"][$id])) {
move_uploaded_file($_FILES["images"]["tmp_name"][$id], $_FILES["images"]["name"][$id]);
echo $_FILES["images"]["tmp_name"][$id] . " Was Succesuflly uploaded \r\n ";
} else {
echo "file didnt exists " . $_FILES["images"]["tmp_name"][$id] . "\r\n ";
}
}
} else {
//No Files were passed through
echo "no files passed through";
}
exit();
Hopefully that answers your question.

How do you access other files stored on an website with JavaScript?

I am trying to write a webpage for a list of files to download. The files are stored with the webpage and I want the webpage to dynamically list all the files in the folder to download. That way when more are added I don't have to modify the webpage. I know how to use JavaScript to create links on the webpage but I need to use it to find the names of the files first.
I found a website that had code for navigating files like a file browser but it only uses a string to store the current location.
This is in the header:
<script type="text/javascript"><!--
var myloc = window.location.href;
var locarray = myloc.split("/");
delete locarray[(locarray.length-1)];
var fileref = locarray.join("/");
//--></script>
this is in the body:
<form>
<input type=button value="Show Files" onClick="window.location=fileref;">
</form>
However this doesn't really help since I am trying to create download links to files not have a file browser.
Edit:
When you host a traditional HTML page you upload the htmlfile and any images or content for the page to what ever server you use.
I want to use javascript to dynamically link to every file hosted with the webpage.
I am trying to combine this with hosting the files in a Dropbox public folder for a simple way to make the files available.
If you want a list of files on the server you will need to use a server-side script to gather their names:
JS--
//use AJAX to get the list of files from a server-side script
$.getJSON('path/to/server-side.php', { 'get_list' : 'true' }, function (serverResponse) {
//check the response to make sure it's a success
if (serverResponse.status == 'success') {
var len = serverResponse.output.length,
out = [];
//iterate through the serverResponse variable
for (var i = 0; i < len; i++) {
//add output to the `out` variable
out.push('<li>' + serverResponse.output[i] + '</li>');
}
//place new serverResponse output into DOM
$('#my-link-container').html('<ul>' + out.join('') + '</ul>');
} else {
alert('An Error Occured');
}
});
PHP--
<?php
//check to make sure the `get_list` GET variable exists
if (isset($_GET['get_list'])) {
//open the directory you want to use for your downloads
$handle = opendir('path/to/directory');
$output = array();
//iterate through the files in this directory
while ($file = readdir($handle)) {
//only add the file to the output if it is not in a black-list
if (!in_array($file, array('.', '..', 'error_log'))) {
$output[] = $file;
}
}
if (!empty($output)) {
//if there are files found then output them as JSON
echo json_encode(array('status' => 'success', 'output' => $output));
} else {
//if no files are found then output an error msg in JSON
echo json_encode(array('status' => 'error', 'output' => array()));
}
} else {
//if no `get_list` GET variable is found then output an error in JSON
echo json_encode(array('status' => 'error', 'output' => array()));
}
?>

Zend_Form Jquery & fileUploadErrorIniSize

Edit, I fixed it by changing my JS to:
$('.zend_form input:not([type="file"]), .zend_form textarea').each(function() {
data[$(this).attr('name')] = $(this).val();
});
Hello,
As I posted earlier, I followed a ZendCast that allowed you to use jQuery to detect and display to users problem with their form.
However, file fields always return: fileUploadErrorIniSize (File 'image_front_url' exceeds the defined ini size" even if the file is within size limits.
TPL For Forms:
<?php $this->headScript()->captureStart(); ?>
$(function() {
$('.zend_form input, .zend_form textarea').blur(function() {
var formElementId = ($(this).parent().prev().find('label').attr('for'));
doValidation(formElementId);
});
});
function doValidation(id) {
var url = '/<?php echo MODULE; ?>/json/validateform/form_name/<?php echo get_class($this->form); ?>';
var data = {};
$('.zend_form input, .zend_form textarea').each(function() {
data[$(this).attr('name')] = $(this).val();
});
$.post(url, data, function(resp) {
$('#'+id).parent().find('.errors').remove();
$('#'+id).parent().append(getErrorHtml(resp[id], id));
}, 'json');
};
function getErrorHtml(formErrors, id) {
var o = '';
if (formErrors != null) {
var o = '<ul id="errors-'+id+'" class="errors">';
for (errorKey in formErrors) {
o += '<li>'+formErrors[errorKey]+'</li>';
}
o += '</ul>';
}
return o;
}
<?php $this->headScript()->captureEnd(); ?>
<?php
if (is_object($this->form) && $this->form->getErrorMessages()) {
echo $this->partial('partials/errors.phtml', array('errors' => $this->form->getErrorMessages(), 'translate' => $this->translate));
}
?>
<?php if (isset($this->errorMsg)) { ?>
<p><?php echo $this->errorMsg; ?></p>
<?php } ?>
<?php echo $this->form; ?>
Which is directed to
<?php
class Administration_JsonController extends Zend_Controller_Action {
public function validateformAction() {
$form_name = $this->_getParam('form_name');
$form = new $form_name();
$data = $this->_getAllParams();
$form->isValidPartial($data);
$json = $form->getMessages();
$this->_helper->json($json);
}
}
Example of returned json:
{"name":{"isEmpty":"Value is required and can't be empty"},"name_url":{"isEmpty":"Value is required and can't be empty"},"image_site_url":{"fileUploadErrorIniSize":"File 'image_site_url' exceeds the defined ini size"},"image_url":{"fileUploadErrorIniSize":"File 'image_url' exceeds the defined ini size"},"image_front_url":{"fileUploadErrorIniSize":"File 'image_front_url' exceeds the defined ini size"},"image_back_url":{"fileUploadErrorIniSize":"File 'image_back_url' exceeds the defined ini size"}}
I noticed a few people had this issue and they said that isValidPartial fixes it, so I changed
$form->isValid($data);
to
$form->isValidPartial($data);
but it didn't fix this issue.
Any ideas?
The problem is that you can't treat file fields in the same manner as regular text fields.
When you call $('input').val(), you get an actual text value for the text field, but for the file field you get the file name - and not the file contents.
Then your script tries to validate your file name as a file and, apparently, fails. In order for file validator to succeed you need to pass actual file contents to the script.
So, basically, you need to upload a file asynchronously to the server to perform all the necessary validations.
Unfortunately, uploading files via Ajax is not quite a trivial thing to do. Your basic options are uploading files via iFrame or swfObject. You can take a look at the broad selection of plugins suitable for this purpose here.
My personal choice for asynchronous file upload would be file-uploader jQuery plugin.
Are you putting an Encrypt type on your form?
I have found two different forum posts about this, including a stack post:
odd Zend_Form_Element_File behavior
You need to add enctype="multipart/form-data" to your form tag.
Basically what is happening is the form is using its default "application/x-www-form-urlencoded" method of encryption before it is sent to the server. File uploading is not supported with this method.

Categories

Resources