I have been following This tutorial on using the JQuery file upload plugin. everything looks fine and when I select a file to upload the browser there are no errors but the file doesn't seem to upload. I could be wrong but I assumed the file would be in the uploads folder in the project directory(eclipse). Here is the code:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Mini Ajax File Upload Form</title>
<!-- Google web fonts -->
<link href="http://fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700" rel='stylesheet' />
<!-- The main CSS file -->
<link href="assets/css/style.css" rel="stylesheet" />
</head>
<body>
<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
<div id="drop">
Drop Here
<a>Browse</a>
<input type="file" name="upl" multiple />
</div>
<ul>
<!-- The file uploads will be shown here -->
</ul>
</form>
<!-- JavaScript Includes -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="assets/js/jquery.knob.js"></script>
<!-- jQuery File Upload Dependencies -->
<script src="assets/js/jquery.ui.widget.js"></script>
<script src="assets/js/jquery.iframe-transport.js"></script>
<script src="assets/js/jquery.fileupload.js"></script>
<!-- Our main JS file -->
<script src="assets/js/script.js"></script>
</body>
</html>
script.js
$(function(){
var ul = $('#upload ul');
$('#drop a').click(function(){
// Simulate a click on the file input button
// to show the file browser dialog
$(this).parent().find('input').click();
});
// Initialize the jQuery File Upload plugin
$('#upload').fileupload({
// This element will accept file drag/drop uploading
dropZone: $('#drop'),
// This function is called when a file is added to the queue;
// either via the browse button, or via drag/drop:
add: function (e, data) {
var tpl = $('<li class="working"><input type="text" value="0" data-width="48" data-height="48"'+
' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>');
// Append the file name and file size
tpl.find('p').text(data.files[0].name)
.append('<i>' + formatFileSize(data.files[0].size) + '</i>');
// Add the HTML to the UL element
data.context = tpl.appendTo(ul);
// Initialize the knob plugin
tpl.find('input').knob();
// Listen for clicks on the cancel icon
tpl.find('span').click(function(){
if(tpl.hasClass('working')){
jqXHR.abort();
}
tpl.fadeOut(function(){
tpl.remove();
});
});
// Automatically upload the file once it is added to the queue
var jqXHR = data.submit();
},
progress: function(e, data){
// Calculate the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);
// Update the hidden input field and trigger a change
// so that the jQuery knob plugin knows to update the dial
data.context.find('input').val(progress).change();
if(progress == 100){
data.context.removeClass('working');
}
},
fail:function(e, data){
// Something has gone wrong!
data.context.addClass('error');
}
});
// Prevent the default action when a file is dropped on the window
$(document).on('drop dragover', function (e) {
e.preventDefault();
});
// Helper function that formats the file sizes
function formatFileSize(bytes) {
if (typeof bytes !== 'number') {
return '';
}
if (bytes >= 1000000000) {
return (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= 1000000) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
}
});
upload.php
<?php
// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif','zip');
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/'.$_FILES['upl']['name'])){
echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
All the other required js files are also present. When i run it on tomcat, my output looks like this:
I refreshed the project as well so that's not it. Any help would be great, thanks.
You are not running PHP on the server so the upload isn't saved anywhere.
You need to install PHP on the server, move to a server that has PHP installed or change to another language.
It looks like you're using Windows. You could try using WAMP-server.
Related
I am trying connect my button in my html to my javascript file. I have been using this method for weeks and all of a sudden it stopped working and now I am receiving an error, "will_be_set_after_endpoints_apis_loaded is not defined at HTMLInputElement.onclick" and when I changed it to a function call like "greetByName();" it says method not defined which makes me think that the javascript file isn't being recognized. I will share snippets of my code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>FLINDER</title>
<meta charset="UTF-8">
<script src="hello.js"></script>
<!-- Load the Google APIs Javascript client library -->
<!-- Then call the init function, which is defined in hello.js -->
<script src="https://apis.google.com/js/client.js?onload=init">
</script>
</head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<P><input id="input_greet_name" type="button" value="Please wait..."
onclick="will_be_set_after_endpoints_apis_loaded"></P>
JS File:
package com.google.training.helloworld;
//<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
function init() {
// You need to pass the root path when you load your API
// otherwise calls to execute the API run into a problem
// rootpath will evaulate to either of these, depending on where the
app is running:
// //localhost:8080/_ah/api
// //your-app-id/_ah/api
var rootpath = "//" + window.location.host + "/_ah/api";
// Load the helloworldendpoints API
// If loading completes successfully, call loadCallback function
gapi.client.load('helloworldendpoints', 'v1', loadCallback, rootpath);
}
/*
* When helloworldendpoints API has loaded, this callback is called.
*
* We need to wait until the helloworldendpoints API has loaded to
* enable the actions for the buttons in index.html,
* because the buttons call functions in the helloworldendpoints API */
function loadCallback () {
// Enable the button actions
enableButtons ();
}
function enableButtons () {
// Set the onclick action for the first button
//btn = document.getElementById("input_greet_generically");
//btn.onclick= function(){greetGenerically();};
// Update the button label now that the button is active
//btn.value="Submit";
// Set the onclick action for the second button
btn = document.getElementById("input_greet_name");
btn.onclick= function(){greetByName();};
// Update the button label now that the button is active
btn.value="Submit";
}
function greetByName () {
var loc;
var sal;
var schoolTypes;
var request;
loc = document.getElementById("loc").value;
sal = document.getElementById("sal").value;
var temp = loc;
schoolTypes = document.getElementById("schoolTypes").value;
var temps = schoolTypes;
if(loc == "" || sal == "" || schoolTypes == "")
{
alert("Please enter all valid options");
request = gapi.client.helloworldendpoints.sayHello();
}
}
I am trying to upload a file to upload directory.From there i am trying to insert the entire file into the database.Here is a script which tells how i uploaded the file.I need the name of the file that i just uploaded for inserting the data into the database.
here is the script
Controller/FileUploadsController.php
<?php
class FileUploadsController extends AppController {
public Function index(){
// A list of permitted file extensions
$allowed = array('csv');
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
echo $extension;
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/'.$_FILES['upl']['name'])){;
echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
}
}
View/FileUploads/index.ctp
<head>
<meta charset="utf-8"/>
<title>Mini Ajax File Upload Form</title>
<!-- Google web fonts -->
<link href="http://fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700" rel='stylesheet' />
<!-- The main CSS file -->
<link href="assets/css/style.css" rel="stylesheet" />
</head>
<body>
<form id="upload" method="post" action="FileUploads" enctype="multipart/form-data">
<div id="drop">
Drop Here
<a>Browse</a>
<input type="file" name="upl" multiple />
</div>
<ul>
<!-- The file uploads will be shown here -->
</ul>
</form>
<!-- JavaScript Includes -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="assets/js/jquery.knob.js"></script>
<!-- jQuery File Upload Dependencies -->
<script src="assets/js/jquery.ui.widget.js"></script>
<script src="assets/js/jquery.iframe-transport.js"></script>
<script src="assets/js/jquery.fileupload.js"></script>
<!-- Our main JS file -->
<script src="assets/js/script.js"></script>
<!-- Only used for the demos. Please ignore and remove. -->
<script src="http://cdn.tutorialzine.com/misc/enhance/v1.js" async></script>
</body>
</html>
script.js
$(function(){
var ul = $('#upload ul');
$('#drop a').click(function(){
// Simulate a click on the file input button
// to show the file browser dialog
$(this).parent().find('input').click();
});
// Initialize the jQuery File Upload plugin
$('#upload').fileupload({
// This element will accept file drag/drop uploading
dropZone: $('#drop'),
// This function is called when a file is added to the queue;
// either via the browse button, or via drag/drop:
add: function (e, data) {
var tpl = $('<li class="working"><input type="text" value="0" data-width="48" data-height="48"'+
' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>');
// Append the file name and file size
tpl.find('p').text(data.files[0].name)
.append('<i>' + formatFileSize(data.files[0].size) + '</i>');
// Add the HTML to the UL element
data.context = tpl.appendTo(ul);
// Initialize the knob plugin
tpl.find('input').knob();
// Listen for clicks on the cancel icon
tpl.find('span').click(function(){
if(tpl.hasClass('working')){
jqXHR.abort();
}
tpl.fadeOut(function(){
tpl.remove();
});
});
// Automatically upload the file once it is added to the queue
var jqXHR = data.submit();
},
progress: function(e, data){
// Calculate the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);
// Update the hidden input field and trigger a change
// so that the jQuery knob plugin knows to update the dial
data.context.find('input').val(progress).change();
if(progress == 100){
data.context.removeClass('working');
}
},
fail:function(e, data){
// Something has gone wrong!
data.context.addClass('error');
}
});
// Prevent the default action when a file is dropped on the window
$(document).on('drop dragover', function (e) {
e.preventDefault();
});
// Helper function that formats the file sizes
function formatFileSize(bytes) {
if (typeof bytes !== 'number') {
return '';
}
if (bytes >= 1000000000) {
return (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= 1000000) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
}
});
it is a simple jquery file uploader script working file.there might be a problem in FileUploadsController.php. I need help in getting the name of the file that uploaded.
I have an html file that is supposed to display every picture in the uploads directory, however it does not recognize an uploads directory. I am using a nodejs server. Here is my html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>gummy bear</title>
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link href="css/styles.css" rel="stylesheet">
</head>
<body>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script>
var dir = "/uploads/";
var fileextension = ".jpg";
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='" + dir + filename + "'>");
});
}
});
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
and here is what my directory layout looks like:
app.js css index.html javascripts LICENSE node_modules package.json README.md upload.html uploads
and inside of uploads is:
➜ uploads ls
1.jpg
Thanks in advance!
Looking through the sample code it seems like the HTML file expects some HTML to be returned from http://localhost:3000/uploads.
The questions is why does the /uploads endpoint not return anything but instead returns a 404 response?
The answer to this would lie in the main executable Javascript file in the node.js application. Likely a file called server.js or index.js.
Here is an example of how you would go about creating the correct node.js application for you HTML file to work:
server.js
app.all('/uploads', function (req, res) {
var folder = './public/uploads',
html = '<html><body>##files##</body></html>';
fs.readdir(folder, (err, files) => {
var fileHrefs = '';
files.forEach(function (file) {
fileHrefs += '' + file + '';
});
html = html.replace('##files##', fileHrefs);
res.send(err || html);
})
});
This snippet of code iterates over all files in the uploads directory and wraps them in an a tag which is then returned by the server.
index.html
To make your index HTML file work a couple small changes need to be made:
change $(data).find() to $(data).filter()
remove the directory from the image source. change <img src='" + dir + filename + "'> to <img src='" + filename + "'>
Complete working sample
You can also find the whole working sample here: https://github.com/kohlikohl/list-images-in-dir
I am trying to create a zip file using jsZip . The contents of the zip file are images from the web.
I have created the following code. But when i run it all am getting is an empty zip file of 22kb.
<html>
<body>
<script type="text/javascript" src="jszip.js"></script>
<script type="text/javascript" src="FileSaver.js"></script>
<script type="text/javascript" src="jszip-utils.min.js"></script>
<script>
var imgLinks = ["url1", "url2", "url3"];
function create_zip() {
var zip = new JSZip();
for (var i = 0; i < imgLinks.length; i++) {
JSZipUtils.getBinaryContent(imgLinks[i], function(err, data) {
if (err) {
alert("Problem happened when download img: " + imgLink[i]);
console.erro("Problem happened when download img: " + imgLink[i]);
deferred.resolve(zip); // ignore this error: just logging
// deferred.reject(zip); // or we may fail the download
} else {
zip.file("picture" + i + ".jpg", data, {
binary: true
});
deferred.resolve(zip);
}
});
}
var content = zip.generate({
type: "blob"
});
saveAs(content, "downloadImages.zip");
}
</script>
<br/>
<br/>
<center>
Click the button to generate a ZIP file
<br/>
<input id="button" type="button" onclick="create_zip()" value="Create Zip" />
</center>
</body>
</html>
(url1 , url2 and url3 replaced by image urls i want to download).
Why am i getting these empty zip files?
JSZipUtils.getBinaryContent is asynchronous : the content will be added after the call to zip.generate(). You should wait for all images before generating the zip file.
Edit :
If the files you are loading are on a different server, this server need to send additional HTTP headers, like Access-Control-Allow-Origin: server-hosting-the-page.com. The Firefox or Chrome debug console will show an error in that case. The js library can't detect a CORS issue (see here) and will trigger a success with an empty content.
i am making an application in which i need to directly pick up the .doc or .docx files from the file system and load them on the page. Can you help me with the code ?
There is a problem with using a normal file reader in opening these files , can anyone clarify why is it happenning ?
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-libs="sap.ui.commons"
data-sap-ui-theme="sap_goldreflection">
</script>
<!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs'
if required -->
<body>
<input type="file" id="files" name="file" />
<div id="byte_content"></div>
<script>
function readBlob() {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = 0;
var stop = file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById('byte_content').textContent = evt.target.result;
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
$("document").ready(function () {
$("#files").change(function () {
readBlob();
});
});
</script>
</body>
</html>
You could take a look at the DocumentCloud project which has a bunch of components including an HTML5 Open Source Document viewer - NYtimes Document viewer - hosted on git (Apache license)