I was curious if using input type = "file" will store the actual file that was selected? If so, how would I display that file, preferably a photo, inside of a div or span? I'm working on a project where people can sell their stuff. I'm looking for a way to display the picture that a user submits, somewhat like the way Facebook does.
How would you display that file
You would have a server recieve the form data, and then do one of the following
Serve the posted file from the server itself.
Upload the file to another server or cloud which serves the file.
You can then send this hosted URL to the client as an image source to show it.
You'll want to check the file to make sure it is not mallicious, and probably randomise the name to make attacking the system harder, to prevent someone from uploading a PHP shell and taking over the server.
I have figured out a way using javascript to display the picture after it's been selected for upload. The code is as follows (Entire document).
<!doctype html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/reset.css"> <!-- CSS reset -->
<link rel="stylesheet" href="css/style.css"> <!-- Resource style -->
<script src="js/modernizr.js"></script> <!-- Modernizr -->
<script>
function displayProduct(){
var product = document.getElementById("productTitle").value;
var productDesc = document.getElementById("productDescription").value;
var files = document.getElementById("blah").src;
document.getElementById("showProduct").style.display = "block";
document.getElementById("productHead").innerHTML = product;
document.getElementById("productD").innerHTML = productDesc;
document.getElementById("photo").innerHTML = files;
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#photo')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
<title>XXXXXXXXX dot Com</title>
</head>
<body>
<header>
<img src = "brownBag.jpg" width = "8%" style = "float: left;">
<h3>Deal Finder dot Com</h3>
<nav class="cd-stretchy-nav">
<a class="cd-nav-trigger" href="#0">
Menu
<span aria-hidden="true"></span>
</a>
<ul>
<li><span>The Homepage of Nephilim42 Coding</span></li>
<li><span>CSS Portfolio Project</span></li>
<li><span>Javascript Portfolio Project</span></li>
<li><span>Play a game of Darts! Powered by Javascript</span></li>
<li><span>My First Business Website</span></li>
</ul>
<span aria-hidden="true" class="stretchy-nav-bg"></span>
</nav>
</header>
<main class="cd-main-content">
<label for = "form">
<form name = "postForm" id = "postForm" method = "POST" action = "">
<p>What are you selling?
<input type = "text" name = "productTitle" id = "productTitle">
</p><br>
<p>Please describe your product.
<textarea name = "productDescription" id = "productDescription" cols = "50" rows = "6"></textarea>
</p><br>
<p>Upload Picture:
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</p>
<input type = "button" name = "post" id = "post" value = "POST" onClick = "displayProduct()"><br>
</form>
<div id = "showProduct">
<p>Product Title:
<span id = "productHead"></span>
</p><br>
<p>Product Description:
<span id = "productD"></span>
</p><br>
<p>Uploaded Photo:
<span id = "photo"></span>
</p>
</div>
<script src="js/jquery-2.1.4.js"></script>
<script src="js/main.js"></script> <!-- Resource jQuery -->
</body>
</html>
Below are some attached images. Unfortunately because I have low reputation here on stackOverflow, only the link will attach. Which do work when copied and pasted into the URL search bar. These images show the steps with what happens when uploading a file. unfortunately I have ran into a problem, but I will work on fixing it. The problem is on image #2. The second chunk of javascript in the readURL function is a failed attempt to rectify that.
Image 1) Upload button clicked, selecting image
Image 2) After image is selected and posted, the value of the file is sent via innerHTML to a span. The value seems to be a super long character string rather than the image in the span. I will try to work on this and fix it, and post on this thread the solution.
1 https://i.stack.imgur.com/2Ev4b.png
2 https://i.stack.imgur.com/L0ymG.png
Related
I'd like to use a style sheet from Wikipedia. For that, I'm fetching this style sheet. When trying to
pass the url fetched using ajax to the head of my html document, the url retrieved behave unexpectedly.
First, I simply try to use the url as it is fetched :
var stylesheetElem = doc.querySelector('head link[rel="stylesheet"]');
Here is the full code :
<!DOCTYPE html>
<!-- testing purpose file, used for trying to print a correctly formatted wikipedia page -->
<html>
<head>
<meta charset="utf-8"/>
<title> game setup </title> <!-- Titre de l'onglet -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
</head>
<body style="background-color:white;">
<div class='container'>
<h1 id="title">MiniWiki</h1>
<div id="content"></div>
</div>
<script>
function loadPage() {
"use strict";
var url, doc;
console.log("IN LOADPAGE")
url = 'https://en.wikipedia.org:443/api/rest_v1/page/html/' + 'Ancient_Egypt';
// fetch the article data
return $.ajax(url).then(function (data) {
doc = (new DOMParser()).parseFromString(data, 'text/html');
// Use mediawiki content stylesheet
var stylesheetElem = doc.querySelector('head link[rel="stylesheet"]');
console.log("SHOW stylesheetElem");
console.log(stylesheetElem);
$('head').append(stylesheetElem);
//Update content
var contentElem = document.getElementById('content');
var $content = $(contentElem).empty();
Array.from(doc.body.attributes).forEach(function (attr) {
$content.attr(attr.name, attr.value);
});
$content.append(Array.from(doc.body.children));
});
}
loadPage();
</script>
In this case, the url fetched is
<link rel="stylesheet" href="/w/load.php?lang=en&modulening.con...%7Cext.cite.styles&only=styles&skin=vector">
I was expecting that it would also include https://en.wikipedia.org/ at the beginning of the url like this :
<link rel="stylesheet" href="https://en.wikipedia.org/w/load.php?lang=en&modulening.con...%7Cext.cite.styles&only=styles&skin=vector">
Since it dit not, I thought I could add it myself by simply adding this line of code just
before the line
console.log("SHOW stylesheetElem");
stylesheetElem.href = "http://en.wikipedia.org" + stylesheetElem.href
when printing the stylesheetElem url, this unexpectedly returns the following url :
http://en.wikipedia.orgfile//en.wikipedia.org/w/load.php?...kin=vector
What happened here ? Why didn't I get the following correct url ?
http://en.wikipedia.org/w/load.php?...kin=vector
The dots (...) indicate that the developer tools have left out part of the url. You copy that instead of the real url, which you can see when you do "View Page Source":
/w/load.php?lang=en&modules=ext.uls.interlanguage%7Cext.visualEditor.desktopArticleTarget.noscript%7Cext.wikimediaBadges%7Cskins.vector.styles.legacy&only=styles&skin=vector
I am trying to make a drop-down box (select), and get the options from a sheet, but I can't get it to work. Actually the problem is, that I have to wait for the script.run to finish, before I add to the select. I therefore moved the add, to the successhandler-function, but somehow it doesn't do anything. If I run it, as this I only get option 1 and 2.
My document look like this:
The server-side code looks like this, stripped down to nothing, just to make sure the miss isn't coming from here.
<!DOCTYPE html>
<html>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta dato="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="container">
<div class="row">
<form action="/action_page.php" id="inputform">
<div class="input-field">
<input id="tekst" type="text" class="validate">
<label class="active" for="tekst">Tekst</label>
</div>
<div class="input-field">
<select name="Choose" id="Choose">
<option value="" selected disabled hidden> Choose</option>
</select>
</div>
</form><!--- end form
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
var instance = M.FormSelect.getInstance(elem);
});
var konto = "Choose";
var x = document.getElementById("Choose");
var option = document.createElement("option");
option.text = "Option 1";
x.add(option);
google.script.run.withSuccessHandler(fillOption).getOption();
var option = document.createElement("option");
option.text = "Option 2";
x.add(option);
function fillOption(){
var konto = "Choose";
var x = document.getElementById("Choose");
var option = document.createElement("option");
option.text = "Option 3";
x.add(option);
}
</script>
</body>
</html>
The serverside code looks like this, stripped down to nothing, just to make sure the miss isnt comming from here.
function onOpen() {
var template = HtmlService.createTemplateFromFile("userform");
var html = template.evaluate();
html.setTitle("Just testing select").setHeight(500).setWidth(700);
SpreadsheetApp.getUi().showModelessDialog(html, "testing");
}
function getOption() {
}
I'm working on a project, where the user will use side-bar html page, as a form to update a sheet (very basic operation).
I'm having issue with the autocomplete part.
I'm a beginner to code html with google apps script, so please let me know if you don't have enough information.
The script is supposed to get names from a google sheets, and populate it to the autocomplete item.
I followed a tutorial doing practically the same operation, but based on a web app using a google spreadsheet ==> this one worked perfectly for me.
The challenge is now into adapting it to a sidebar page on google sheet ==> does not work at the moment.
I've been struggling for hours and trying different options, so here is :
- What I made on gs page :
var ss = SpreadsheetApp.getActiveSpreadsheet();
var shEmployees = ss.getSheetByName("Employes");
var colEmploye_nomPrenom=1;
var colEmploye_barcode=colEmploye_nomPrenom+1;
var colEmploye_mail=colEmploye_barcode+1;
var colEmploye_metier=colEmploye_mail+1;
function loadBasicForm(){
var tmp=HtmlService.createTemplateFromFile("basicHtmlForm");
var html = tmp.evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
html.setTitle("Test");
SpreadsheetApp.getUi().showSidebar(html);
}//function loadBasicForm(){
function getUnactiveEmployees(){
var ws=shEmployees;
var values= ws.getRange(1,1,ws.getLastRow(),colEmploye_metier).getValues();
var options={};
for (var i=0;i<values.length;i++){
var name=values[i][colEmploye_nomPrenom-1];
var job=values[i][colEmploye_metier-1];
var testUnactive_OK=job=="Désactivé";
if (testUnactive_OK){
options[name]=null;
}//if (testUnactive_OK){
}//for (var i=0;i<values.length;i++){
Logger.log (options);//returns {employee1=null, employee8=null, employee3=null, employee9=null, employee5=null, employee10=null, employee7=null, employee6=null, employee11=null, employee4=null, employee2=null}
return options;
}
What I made on html page :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"><!--Import Google Icon Font-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"><!-- Compiled and minified CSS -->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/> <!--Let browser know website is optimized for mobile-->
</head>
<body>
<div class="container">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input type="text" id="searchedEmployee" class="autocomplete" required><!-- ISSUE AT FILLING IT -->
<label for="searchedEmployee">Spell a Name</label>
</div>
</div><!-- END ROW -->
</div ><!-- END CONTAINER -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <!-- Compiled and minified JavaScript -->
<script>
document.addEventListener('DOMContentLoaded', function() {
google.script.run.withSuccessHandler(populateEmployees).getUnactiveEmployees();
});
function populateEmployees(employees){
var autocomplete = document.getElementById('searchedEmployee');
var instances = M.Autocomplete.init(autocomplete, { data:employees });
}
</script>
</body>
</html>
At this point, the side-page is displayed, but nothing is suggested at typing, for example : "emp" for "employeeX" expected with the "getUnactiveEmployees" list.
EDIT :
My issue is not about displaying - that does displaying.
What I cannot do, is to allow the script to autocomplete the item "searchedEmployee". I guess there is an error on this part :
document.addEventListener('DOMContentLoaded', function() {
google.script.run.withSuccessHandler(populateEmployees).getUnactiveEmployees();
});
Do you have any idea of what I did wrong ?
Many thanks !
Try this:
function loadBasicForm(){
SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('basicHtmlForm').setTitle('Test'));
}
I've been trying out AngularJS by creating a simple gallery that gets images from a json file, but somehow I can't seem to display the data.
index.html:
<!DOCTYPE html>
<html ng-app="portfolioApp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div ng-controller="GalleryController" >
<ul>
<li ng-repeat="image in gallery.galleryData">
<a ng-href="">{{image.IMAGE_WIDTH}}
<img class="thumbnail" ng-src="{{IMAGE_LOCATION+image.image}}" />
</a>
</li>
</ul>
</div>
</body>
</html>
app.js:
var app = angular.module('portfolioApp',[]);
app.controller('GalleryController',['$http', function($http){
var gallery = this;
gallery = [];
gallery.IMAGE_WIDTH = 405;
gallery.IMAGE_LOCATION = "http://rabidgadfly.com/assets/angular/gallery1/";
$http.get("images.json").success(function(data){
gallery.galleryData = data;
});
}]);
I think the issue has something to do with the scope of the gallery variable, but i'm not sure: http://i.stack.imgur.com/VBGku.png
Scopes provide APIs ($apply) to propagate any model changes through
the system into the view from outside of the "Angular realm"
(controllers, services, Angular event handlers).
So you should add gallery to $scope then it can be accessed in the View:
var app = angular.module('portfolioApp',[]);
app.controller('GalleryController',['$http', '$scope', function($http, $scope){
$scope.gallery = [];
$scope.gallery.IMAGE_WIDTH = 405;
$scope.gallery.IMAGE_LOCATION = "http://rabidgadfly.com/assets/angular/gallery1/";
$http.get("images.json").success(function(data){
$scope.gallery.galleryData = data;
});
}]);
Sorry for my English, I am a new to jquery mobile and only have basic knowledge about javascript languages in general; I was playing around with a single page website mobile ( I usually use Dreamweaver CS6) and I reached a good result with photoswipe and everything was good since I had just few images. I have added a lot of them so now I would get the images' link dynamically.
In short, I want to start from a folder on my ftp and read all images file within it and create the <li> items for each one. Can I make this job with jquery mobile or should I use a language like php or .Net
I have read some examples around here and on google but they didn't help me a lot, like this one, I am sure it could be an answer for me in it but I don't know how to start
http://docs.phonegap.com/en/2.4.0/cordova_file_file.md.html#DirectoryReader
Here some code I'm using:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<!-- Librerie PhotoSwipe -->
<link rel="stylesheet" type="text/css" href="../PhotoSwipe/photoswipe.css">
<link rel="stylesheet" type="text/css" href="../PhotoSwipe/styles.css">
<script type="text/javascript" src="../PhotoSwipe/klass.min.js"></script>
<script type="text/javascript" src="../PhotoSwipe/code.photoswipe-3.0.5.min.js"></script>
<!-- End PhotoSwipe -->
<script type="text/javascript">
$(document).ready(function(){ var myPhotoSwipe = $("#Gallery a").photoSwipe({ enableMouseWheel: false , enableKeyboard: false, captionAndToolbarAutoHideDelay: 0 }); });
</script>
Then my page
<div data-role="page" id="page">
<div data-role="header">
<h1>Title of my Page</h1>
</div>
<div data-role="content">
<ul id="Gallery" class="gallery">
<li>
<a href="../Images/img04.jpg">
<img src="../Images/img04.jpg" alt=""></a>
</li>
</ul>
</div>
When i land on this page everything works fine. Shall I use something like this?
That I took from this website, can I use JSON to accede to my ftp folder and than cycle the content?
Should I put this in a function? If yes who is going to call it?
$("#Photos").live("pagebeforeshow", function(){
$("ul#PhotoList").children().remove('li');
var tag = MyTag
$.getJSON("https://api.instagram.com/v1/tags/" + tag + "/media/recent?callback=?&client_id=####",
function(data){
$.each(data.data, function(i,item){
$("ul#PhotoList").append('<li><img src="' + item.images.low_resolution.url + '" alt="' + item.caption.text + '" width="200" /></li>');
});
});
var photoSwipeInstance = $("ul#PhotoList a").photoSwipe();
});
Any help is appriciated, thank you in advance, I am sure my issue here is my limited knowledge.
You should use pageinit and pagebeforeshow Instead of $(document).ready. Also .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). http://api.jquery.com/live/
Append list Items:
$("#PhotoList").append('<li><a href="..
When you finish refresh the list to display your new list:
$('#PhotoList').listview('refresh');
Update:
I use php programs on my server in order to retrieve json strings. Something like this...
xhr = new XMLHttpRequest();
xhr.open("GET","http://192.168.100.2/sr/quotelisttest?name="+s,true);
xhr.send("");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4){
alert(xhr.readyState);
alert(xhr.responseText);
var v = JSON.parse(xhr.responseText);