creating an image uploader with preview in php and javascript - javascript

my code does not seem to be able to pull the image from my desktop for a preview. i don't know what. All it was does, is show me a broken image. Here is the code.
javascript
function ajaxFileUpload(upload_field)
{
// Checking file type
var re_text = /\.jpg|\.gif|\.jpeg|\.png|\.gif/i;
var filename = upload_field.value;
if (filename.search(re_text) == -1) {
alert("File should be either jpg or gif or jpeg or png");
upload_field.form.reset();
return false;
}
document.getElementById('picture_preview').innerHTML = '<img src="" width="10%" border="0" />';
upload_field.form.action = 'upload-picture.php';
upload_field.form.target = 'upload_iframe';
upload_field.form.submit();
upload_field.form.action = '';
upload_field.form.target = '';
return true;
}
HTML
<!-- iframe used for ajax file upload-->
<!-- debug: change it to style="display:block" -->
<iframe name="upload_iframe" id="upload_iframe" style="display:none;"></iframe>
<!-- iframe used for ajax file upload-->
<form name="pictureForm" method="post" autocomplete="off" enctype="multipart/form-data">
<div>
<span>Upload Picture :</span>
<input type="file" name="picture" onclick="preview()" id="picture" onchange="return ajaxFileUpload(this);" />
<span id="picture_error"></span>
<div id="picture_preview"></div>
</div>
</form>

Something like this should work:
Javascript
var input = document.getElementById('image_uploader');
var uploadedImage = document.getElementById('uploaded_image');
input.addEventListener('change', onImageInput);
function onImageInput()
{
var imageFile = input.files[0];
var reader = new FileReader();
reader.addEventListener('loadend', onReaderComplete);
reader.readAsDataURL(imageFile);
}
function onReaderComplete(e)
{
uploadedImage.src = e.target.result;
}
HTML
<input type="file" id="image_uploader"/>
<div id="picture_preview"><img id="uploaded_image"/></div>
After this, you can send the image data (src) to the server with AJAX or other stuff like that.

Related

Calling Image File on Google App Scripts to Upload into GoogleDrive

I am trying to set up a way to upload image files into a google drive. It will create a folder using a timeid and place the image inside the folder it created. I am having trouble calling out the image file. This is how I am attempting this, the folder gets created but no image.
Please ignore any missing var for the timeid variable. This is working fine.
Error given:
ReferenceError: imgInp is not defined
Thank you in advance for your help!
Code.gs
var day = d.getDate();
var month = d.getUTCMonth();
var hour = d.getHours();
var minutes = d.getMinutes();
var realmonth = month+1;
var timeid = String(year)+"-"+String(realmonth)+"-"+String(day)+"-"+String(hour)+"-"+String(minutes);
var foldername=timeid;
var parentFolder=DriveApp.getFolderById("##############");
function upload(){
var newFolder=parentFolder.createFolder(timeid);
var folderidlookup = newFolder.getId();
var destination = DriveApp.getFolderById(folderidlookup);
var imgf = imgInp;
var contentType = 'image/jpeg';
var imgf = imgf.getAs(contentType);
destination.createFile(imgf)
}
Html
<form>
<div class="file-field input-field">
<div class="waves-effect waves-light btn" id="wholebtn"><i class="material-icons right">cloud</i>Browse
<input type="file" name="imgInp" id="imgInp" onchange="loadFile(event)">
</div>
<div class="file-path-wrapper">
<input type="text" class="file-path">
</div>
</div>
</form>
<button class="btn waves-effect waves-light" type="submit" name="action" id ="button">Submit
<i class="material-icons right">send</i>
</button>
JS
<script>
document.getElementById("button").addEventListener("click",upload);
function upload(){
google.script.run.upload();
}
</script>
The error you're getting is because you're trying to use a imgInp variable which you don't have it defined in any part of the code. You can get the blob file from the input, convert it to a binary array string, pass it to the server-side and finally use it to create your blob and the given Drive file, for this I used the code from this answer.
Using the examples for how to work with forms and success and failure handlers from the HTML Service guide, I put together the below code which worked successfully uploading the given image:
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
<div class="file-field input-field">
<div class="waves-effect waves-light btn" id="wholebtn"><i class="material-icons right">cloud</i>Browse
<input type="file" name="imgInp" id="imgInp">
</div>
<div class="file-path-wrapper">
<input type="text" class="file-path">
</div>
</div>
<button class="btn waves-effect waves-light" name="action" id="button">Submit
<i class="material-icons right">send</i>
</button>
</form>
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
// Add event listeners
window.addEventListener('load', preventFormSubmit);
document.getElementById("button").addEventListener("click", upload);
// Handler function
function logger(e) {
console.log(e)
}
async function upload() {
// Get all the file data
let file = document.querySelector('input[type=file]').files[0];
// Get binary content, we have to wait because it returns a promise
let fileBuffer = await file.arrayBuffer();
// Get the file content as binary and then convert it to string
const data = (new Uint8Array(fileBuffer)).toString();
// Pass the binary array string to uploadG funciton on code.gs
google.script.run.withFailureHandler(logger).withSuccessHandler(logger).uploadG(data);
}
</script>
</body>
</html>
Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
function uploadG(imgInp){
var parentFolder=DriveApp.getFolderById("[FOLER-ID]");
var newFolder = parentFolder.createFolder('test webApp');
var folderidlookup = newFolder.getId();
var destination = DriveApp.getFolderById(folderidlookup);
var contentType = 'image/jpeg';
// Convert the binary array string to array and use it to create the Blob
var blob = Utilities.newBlob(JSON.parse("[" + imgInp + "]"), contentType);
blob = blob.getAs(contentType);
destination.createFile(blob)
return 'Filed uploaded!';
}
File Upload Dialog
Run upLoadMyDialog() from script editor to get it started. The select file and click upload.
function fileUpload(obj) {
var d=new Date();
var ts=Utilities.formatDate(d, Session.getScriptTimeZone(), "yyyy-MM-dd-HH-mm");
var folder=DriveApp.getFolderById("****** Enter FolderId *******");
var file=folder.createFile(obj.file1).setName(ts);
}
function uploadMyDialog() {
var ss=SpreadsheetApp.getActive();
var html='<form><input type="file" name="file1"/><br /><input type="button" value="Upload" onClick="google.script.run.fileUpload(this.parentNode);" /></form>';
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),"Upload File");
}
With eventListener:
function uploadMyDialog() {
var ss=SpreadsheetApp.getActive();
var html='<form id="f1"><input type="file" name="file1"/><br /><input type="button" value="Upload" id="btn1" /></form>';
html+='<script>window.onload=function(){document.getElementById("btn1").addEventListener("click",function(){google.script.run.fileUpload(document.getElementById("f1"))})}</script>';
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),"Upload File");
}

Upload Image Preview code created by Button doesn't preview the image. Javascript/HTML

So basically i'm stuck. I created a simple upload image button that allows me to preview the image file that i uploaded. I also created a button that creates another upload image button the button is called "Try It". My first upload image button, previews the image correctly, but when i push the "Try It" to create another upload image button and upload another image, it does not preview on the additional upload image button. I just want to know how i can fix it. Below is the full code:
function myFunction() {
var x = document.createElement("INPUT");
x.type = "file";
x.id= "file-upload"
x.onchange= "previewFile()";
document.getElementById("wtf").appendChild(x);
var y = document.createElement('IMG');
y.src= "";
y.alt= "Image preview...";
document.getElementById("preview").appendChild(y);
}
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a File Upload Button.</p>
<button onclick="myFunction()">Try it</button>
<p id="wtf">
<input id="file-upload" type="file" onchange="previewFile()">
</p>
<p id="preview">
<img src="" height="200" alt="Image preview...">
</p>
</body>
</html>
First of all element.onchange takes a function and not a string i changed that also since you need to show different previews with different buttons you need a way to distinguish between them. I am creating a global variable i to keep track of it and passing it to the previewFile function as a parameter.
Here is the code:
var i = 0;
function previewFile(index){
var preview = document.querySelectorAll('img'); //selects the query named img
var file = document.querySelectorAll('input[type=file]')[index].files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview[index].src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
function myFunction() {
i++;
var y = document.createElement('IMG');
y.src= "";
y.alt= "Image preview...";
y.height = 200;
document.getElementById("preview").appendChild(y);
var x = document.createElement("INPUT");
x.type = "file";
x.id= "file-upload"
x.onchange= function(){previewFile(i)};
document.getElementById("wtf").appendChild(x);
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a File Upload Button.</p>
<button onclick="myFunction()">Try it</button>
<p id="wtf">
<input id="file-upload" type="file" onchange="previewFile(0)">
</p>
<p id="preview">
<img src="" height="200" alt="Image preview...">
</p>
</body>
</html>

How to get the text from a csv file in vanilla javascript

I have an input tag:
<input type="file" id="fileUpload" accept=".csv"/>
that gets a csv file from the user. I then store the file into a variable as such:
const csvFile = document.getElementById('fileUpload');
How can I get the contents of the file into one big string if possible?
You can use the FileReader to read files.
<input type="file" id="fileUpload" accept=".csv" onchange="open(event)" />
<script>
var open = function(event) {
var input = event.target.files[0]
var readerObj = new FileReader()
readerObj.onload = function() {
var fileText = readerObj.result
//do something with fileText here....
}
readerObj.readAsText(input)
}
</script>

How to resize an image on preview (no database)

I have script to preview input type=file (image), and generate it into pdf.
There's no problem for a small size of image. Then when i input with size 6Mb, the preview is OK, but when generate to pdf, its take very long time and finally stopped.
So, I want to resize the image size to 200x240px. But i don't know how to do it, because the script using javascript and I still newbie on it.
Please help how to resize it on my script.
Script:
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
console.log(reader.result);
//preview.src = reader.result;
$('#gen-template-frame').contents().find('.logo img').attr('src', reader.result);
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
HTML:
<!doctype html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/magang/front.css">
</head>
<body>
<div class="corpname" contenteditable>RUMAH SAKIT HARUM</div>
<div class="logosisma"><img src="https://sismadigroup.com/idcard/images/background/logo-id-card.png" width="219" height="70" /></div>
<div class="logo">
<!--<img src="resize/resize.php?src=https://sismadigroup.com/idcard/templates/images/avatar/3.jpg&scale=10&q=100">-->
<img src="https://sismadigroup.com/idcard/templates/images/avatar/3.jpg" width="200" height="240" />
</div>
<div class="name highlight" contenteditable>Maesyaroh</div>
<div class="position" contenteditable>Siswa Magang</div>
<div class="nik" contenteditable>SM-0035</div>
<div class="BBP">BENAR BAIK PANTAS</div>
<div class="BBPPoint" style="left:135px;"> . </div>
<div class="BBPPoint" style="left:203px;"> . </div>
</body>
</html>
Edit: PHP for PDF generation:
$frontPage = resolveDependency(stripslashes( $_POST[ "html" ] ));
$backPage = resolveDependency(stripslashes( $_POST[ "html2" ]) );
$frontPageCSS = getCSSFromHTML($frontPage);
$backPageCSS = getCSSFromHTML($backPage);
$mpdf = new mPDF('utf-8', array(75, 114.6), 0, '', 0, 0, 0, 0, 0, 0);
$mpdf->WriteHTML($frontPageCSS, 1);
$mpdf->WriteHTML($frontPage, 0);
$mpdf->WriteHTML('<pagebreak>', 2);
$mpdf->WriteHTML($backPageCSS, 1);
$mpdf->WriteHTML($backPage, 0);
$mpdf->Output('card.pdf', 'I');
Since you are using PHP to generate the PDF you can resize the image with PHP before using it with mPDF. I don't see in your code how you load the image, so I suppose that you use the Image() function for loading the image from a file (in this example $fileName is the name of the input image, replace it with the variable that you use in your code):
// $fileName is the name of the input image
list($width,$height)=getimagesize($fileName); // size of input image
$tempFileName=tempnam(sys_get_temp_dir(),"img").".png";
$newWidth=200;
$newHeight=240;
$image=imagecreatefrompng($fileName); // load the input image
$newImage=imagecreatetruecolor($newWidth,$newHeight); //create an empty image
imagecopyresampled($newImage,$image,0,0,0,0,$newWidth,$newHeight,$width,$height);
imagepng($newImage,$tempFileName,9); // saving the new image to disk
// here you create the PDF using the image saved in $tempFileName
unlink($tempFileName); // and finally we delete the temporal file
I solved the same problem on front-end, before uploading file. You can visit a link!
import imageSqResizer from './image-square-resizer.js'
let resizer = new imageSqResizer(
'image-input',
300,
(dataUrl) =>
document.getElementById('image-output').src = dataUrl;
);
//Get blob
let formData = new FormData();
formData.append('files[0]', resizer.blob);
//get dataUrl
document.getElementById('image-output').src = resizer.dataUrl;

Preview Image without Upload to my server

Hello how i can preview Image without upload to my server in asp.net C# and when i see the image i should press upload to upload to server.
In a HTML5 capable browser you can use the FileReader object to read a file from the users hdd as a base64 encoded string.
You can use this base64 representation with css to show the preview.
In older browsers you will need flash or similar plugin-based code to do it.
Here is a HTML5 example that works in all modern browsers:
<html>
<head>
<script>
var elmFileUpload = document.getElementById('file-upload');
function onFileUploadChange(e) {
var file = e.target.files[0];
var fr = new FileReader();
fr.onload = onFileReaderLoad;
fr.readAsDataURL(file);
}
function onFileReaderLoad(e) {
var bgStyle = "url('" +e.target.result + "')";
elmFileUpload.parentElement.style.background = bgStyle;
};
elmFileUpload.addEventListener('change',onFileUploadChange,false);
</script>
</head>
<body>
<input type="file" id="file-upload"/>
</body>
</html>
See a fiddle of it in action here
Yes it is possible.
Html
<input type="file" accept="image/*" onchange="showMyImage(this)" />
<br/>
<img id="thumbnil" style="width:20%; margin-top:10px;" src="" alt="image"/>
JS
function showMyImage(fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img=document.getElementById("thumbnil");
img.file = file;
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
}
You can get Live Demo from here.

Categories