HTML Drag and Drop and Struts - html

I've been trying to implement the new "Drag and Drop" file and upload feature, using the code from SitePoint.com. I am using Struts Framework as well. FormFile made my uploads easier, I could just hit on "choose" and click away. But, I just can't seem to get it to work the DnD with Struts. The ActionForm validates and reports that the file size is 0! Here's the code from SitePoint.com (js):
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
UploadFile(f);
}
}
// output file information
function ParseFile(file) {
Output(
"<p>File information: <strong>" + file.name +
"</strong> type: <strong>" + file.type +
"</strong> size: <strong>" + file.size +
"</strong> bytes</p>"
);
// display an image
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" /></p>'
);
}
reader.readAsDataURL(file);
}
// display text
if (file.type.indexOf("text") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong></p><pre>" +
e.target.result.replace(/</g, "<").replace(/>/g, ">") +
"</pre>"
);
}
reader.readAsText(file);
}
else{
var reader=new FileReader();
reader.readAsDataURL(file);
}
}
// upload JPEG files
function UploadFile(file) {
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// create progress bar
var o = $id("progress");
var progress = o.appendChild(document.createElement("p"));
progress.appendChild(document.createTextNode("upload " + file.name));
// progress bar
xhr.upload.addEventListener("progress", function(e) {
var pc = parseInt(100 - (e.loaded / e.total * 100));
progress.style.backgroundPosition = pc + "% 0";
}, false);
// file received/failed
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
progress.className = (xhr.status == 200 ? "success" : "failure");
}
};
// start upload
xhr.open("POST", $id("upload").action, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
The jsp (just messing around):
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload File</title>
<link href="css/styles.css" rel="stylesheet" type="text/css" media="all"/>
</head>
<body>
<form id="upload" action="../Repositore/upload_file.do" method="POST" enctype="multipart/form-data">
<fieldset>
<legend>File Upload Form</legend>
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="20000000" />
<div>
<label for="fileselect">File to upload:</label>
<input type="file" id="fileselect" name="file" multiple="multiple" />
<div id="filedrag">or drop files here</div>
</div>
<div>
<table border='0' cellpadding='2'>
<tr><td><label for="ftags">Tags:</label></td><td> <input type='text' id="ftags" name='tags'/></td><td>(Separate by commas)</td></tr>
<tr><td><label for="desc">Description:</label></td><td> <textarea name="description" id="desc" rows="5" cols="30"></textarea></td></tr>
<tr><td><input type="checkbox" name="comment">Yes</input></td></tr>
</div>
<div id="submitbutton">
<button type="submit">Upload file</button>
</div>
</fieldset>
</form>
<div id="progress"></div>
<div id="messages">
<p>Status:</p>
</div>
<script src="js/filedrag.js" type="text/javascript"></script>
What could be wrong? Help?

Related

Trying to upload multiple images but its not uploading [duplicate]

I am using this following code, where user can upload one or multiple files and can delete those files. All the data is stored in form_data.
Untill now I am not able to make the file upload functionality working.
index.php
<input id="avatar" type="file" name="avatar[]" multiple />
<button id="upload" value="Upload" type="button">upload</button>
<div class="preview">
</div>
<div class="return_php"></div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
$(document).ready(function () {
var form_data = new FormData();
var number = 0;
/* WHEN YOU UPLOAD ONE OR MULTIPLE FILES */
$(document).on('change', '#avatar', function () {
console.log($("#avatar").prop("files").length);
len_files = $("#avatar").prop("files").length;
for (var i = 0; i < len_files; i++) {
var file_data = $("#avatar").prop("files")[i];
form_data.append(file_data.name, file_data);
number++;
var construc = '<img width="200px" height="200px" src="' +
window.URL.createObjectURL(file_data) + '" alt="' + file_data.name + '" />';
$('.preview').append(construc);
}
});
/* WHEN YOU CLICK ON THE IMG IN ORDER TO DELETE IT */
$(document).on('click', 'img', function () {
var filename = $(this).attr('alt');
var newfilename = filename.replace(/\./gi, "_");
form_data.delete($(this).attr('alt'))
$(this).remove()
});
/* UPLOAD CLICK */
$(document).on("click", "#upload", function () {
$.ajax({
url: "upload.php",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with form_data
type: 'post',
success: function (data) {
$('.return_php').html(data);
}
})
})
});
</script>
upload.php
<?php
//upload.php
var_export($_FILES); // this final output that i want to upload
?>
HTML
<div class="col-md-6" align="right">
<label>Select Multiple Files</label>
</div>
<div class="col-md-6">
<input type="file" name="files" id="files" multiple />
</div>
<div style="clear:both"></div>
<br />
<br />
<div id="uploaded_images"></div>
JavaScript
$('#files').change(function(){
var files = $('#files')[0].files;
var error = '';
var form_data = new FormData();
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
error += "Invalid " + count + " Image File"
}
else
{
form_data.append("files[]", files[count]);
}
}
if(error == '')
{
$.ajax({
url:"url",
method:"POST",
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function()
{
$('#uploaded_images').html("<label class='text-success'>Uploading...</label>");
},
success:function(data)
{
$('#uploaded_images').html(data);
$('#files').val('');
}
})
}
else
{
alert(error);
}
});
Not same as your question but you can try like this.
Here is your working code.
There were several problem with your code
Incorrect brace closing in ajax call.
Your name field in form data was invalid
You were requesting form_data as index in the $_FILES array
No use of number variable
index.php
<input id="avatar" type="file" name="avatar[]" multiple="multiple"
/>
<button id="upload" value="Upload" type="button">upload</button>
<div class="preview">
</div>
<div class="return_php"></div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js" ></script>
<script>
$(document).ready(function(){
var form_data = new FormData();
/* WHEN YOU UPLOAD ONE OR MULTIPLE FILES */
$(document).on('change','#avatar',function(){
$('.preview').html("");
len_files = $("#avatar").prop("files").length;
for (var i = 0; i < len_files; i++) {
var file_data = $("#avatar").prop("files")[i];
form_data.append("avatar[]", file_data);
var construc = '<img width="200px" height="200px" src="' + window.URL.createObjectURL(file_data) + '" alt="' + file_data.name + '" />';
$('.preview').append(construc);
}
});
/* WHEN YOU CLICK ON THE IMG IN ORDER TO DELETE IT */
$(document).on('click','img',function(){
var filename = $(this).attr('alt');
var newfilename = filename.replace(/\./gi, "_");
form_data.delete($(this).attr('alt'));
$(this).remove();
});
/* UPLOAD CLICK */
$(document).on("click", "#upload", function() {
$.ajax({
url: "upload.php",
dataType: 'image/png',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with form_data
type: 'post',
success: function(data) {
//console.log("data")'
}
});
});
});
</script>
upload.php
<?php
//upload.php
$output = '';
if(is_array($_FILES) && !empty($_FILES['avatar']))
{
foreach($_FILES['avatar']['name'] as $key => $filename)
{
$file_name = explode(".", $filename);
$allowed_extension = array("jpg", "jpeg", "png", "gif");
if(in_array($file_name[1], $allowed_extension))
{
$new_name = rand() . '.'. $file_name[1];
$sourcePath = $_FILES["avatar"]["tmp_name"][$key];
$targetPath = "uploads/".$new_name;
move_uploaded_file($sourcePath, $targetPath);
}
}
$images = glob("uploads/*.*");
foreach($images as $image)
{
$output .= '<div class="col-md-1" align="center" ><img src="' . $image .'" width="100px" height="100px" style="margin-top:15px; padding:8px; border:1px solid #ccc;" /></div>';
}
echo $output;
}
?>

Show the uploaded file on the home page [duplicate]

I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image.
How can I do this?
imgInp.onchange = evt => {
const [file] = imgInp.files
if (file) {
blah.src = URL.createObjectURL(file)
}
}
<form runat="server">
<input accept="image/*" type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
There are a couple ways you can do this. The most efficient way would be to use URL.createObjectURL() on the File from your <input>. Pass this URL to img.src to tell the browser to load the provided image.
Here's an example:
<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="output"/>
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
}
};
</script>
You can also use FileReader.readAsDataURL() to parse the file from your <input>. This will create a string in memory containing a base64 representation of the image.
<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="output"/>
<script>
var loadFile = function(event) {
var reader = new FileReader();
reader.onload = function(){
var output = document.getElementById('output');
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
};
</script>
One-liner solution:
The following code uses object URLs, which is much more efficient than data URL for viewing large images (A data URL is a huge string containing all of the file data, whereas an object URL, is just a short string referencing the file data in-memory):
<img id="blah" alt="your image" width="100" height="100" />
<input type="file"
onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">
Generated URL will be like:
blob:http%3A//localhost/7514bc74-65d4-4cf0-a0df-3de016824345
Try This
To PREVIEW the image before uploading it to the SERVER from the Browser without using Ajax or any complicated functions.
It needs an "onChange" event to load the image.
function preview() {
frame.src=URL.createObjectURL(event.target.files[0]);
}
<form>
<input type="file" onchange="preview()">
<img id="frame" src="" width="100px" height="100px"/>
</form>
To preview multiple image click here
The answer of LeassTaTT works well in "standard" browsers like FF and Chrome.
The solution for IE exists but looks different. Here description of cross-browser solution:
In HTML we need two preview elements, img for standard browsers and div for IE
HTML:
<img id="preview"
src=""
alt=""
style="display:none; max-width: 160px; max-height: 120px; border: none;"/>
<div id="preview_ie"></div>
In CSS we specify the following IE specific thing:
CSS:
#preview_ie {
FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)
}
In HTML we include the standard and the IE-specific Javascripts:
<script type="text/javascript">
{% include "pic_preview.js" %}
</script>
<!--[if gte IE 7]>
<script type="text/javascript">
{% include "pic_preview_ie.js" %}
</script>
The pic_preview.js is the Javascript from the LeassTaTT's answer. Replace the $('#blah') whith the $('#preview') and add the $('#preview').show()
Now the IE specific Javascript (pic_preview_ie.js):
function readURL (imgFile) {
var newPreview = document.getElementById('preview_ie');
newPreview.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgFile.value;
newPreview.style.width = '160px';
newPreview.style.height = '120px';
}
That's is. Works in IE7, IE8, FF and Chrome. Please test in IE9 and report.
The idea of IE preview was found here:
http://forums.asp.net/t/1320559.aspx
http://msdn.microsoft.com/en-us/library/ms532969(v=vs.85).aspx
Short two-liner
This is size improvement of cmlevy answer - try
<input type=file oninput="pic.src=window.URL.createObjectURL(this.files[0])">
<img id="pic" />
I have edited #Ivan's answer to display "No Preview Available" image, if it is not an image:
function readURL(input) {
var url = input.value;
var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
var reader = new FileReader();
reader.onload = function (e) {
$('.imagepreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}else{
$('.imagepreview').attr('src', '/assets/no_preview.png');
}
}
Here's a multiple files version, based on Ivan Baev's answer.
The HTML
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
JavaScript / jQuery
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
Requires jQuery 1.8 due to the usage of $.parseHTML, which should help with XSS mitigation.
This will work out of the box, and the only dependancy you need is jQuery.
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.
Clean and simple
JSfiddle
This will be useful when you want The event to triggered indirectly from a div or a button.
<img id="image-preview" style="height:100px; width:100px;" src="" >
<input style="display:none" id="input-image-hidden" onchange="document.getElementById('image-preview').src = window.URL.createObjectURL(this.files[0])" type="file" accept="image/jpeg, image/png">
<button onclick="HandleBrowseClick('input-image-hidden');" >UPLOAD IMAGE</button>
<script type="text/javascript">
function HandleBrowseClick(hidden_input_image)
{
var fileinputElement = document.getElementById(hidden_input_image);
fileinputElement.click();
}
</script>
TO PREVIEW MULTIPLE FILES using jquery
$(document).ready(function(){
$('#image').change(function(){
$("#frames").html('');
for (var i = 0; i < $(this)[0].files.length; i++) {
$("#frames").append('<img src="'+window.URL.createObjectURL(this.files[i])+'" width="100px" height="100px"/>');
}
});
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="file" id="image" name="image[]" multiple /><br/>
<div id="frames"></div>
</body>
Example with multiple images using JavaScript (jQuery) and HTML5
JavaScript (jQuery)
function readURL(input) {
for(var i =0; i< input.files.length; i++){
if (input.files[i]) {
var reader = new FileReader();
reader.onload = function (e) {
var img = $('<img id="dynamic">');
img.attr('src', e.target.result);
img.appendTo('#form1');
}
reader.readAsDataURL(input.files[i]);
}
}
}
$("#imgUpload").change(function(){
readURL(this);
});
}
Markup (HTML)
<form id="form1" runat="server">
<input type="file" id="imgUpload" multiple/>
</form>
In React, if the file is in your props, you can use:
{props.value instanceof File && (
<img src={URL.createObjectURL(props.value)}/>
)}
How about creating a function that loads the file and fires a custom event. Then attach a listener to the input. This way we have more flexibility to use the file, not just for previewing images.
/**
* #param {domElement} input - The input element
* #param {string} typeData - The type of data to be return in the event object.
*/
function loadFileFromInput(input,typeData) {
var reader,
fileLoadedEvent,
files = input.files;
if (files && files[0]) {
reader = new FileReader();
reader.onload = function (e) {
fileLoadedEvent = new CustomEvent('fileLoaded',{
detail:{
data:reader.result,
file:files[0]
},
bubbles:true,
cancelable:true
});
input.dispatchEvent(fileLoadedEvent);
}
switch(typeData) {
case 'arraybuffer':
reader.readAsArrayBuffer(files[0]);
break;
case 'dataurl':
reader.readAsDataURL(files[0]);
break;
case 'binarystring':
reader.readAsBinaryString(files[0]);
break;
case 'text':
reader.readAsText(files[0]);
break;
}
}
}
function fileHandler (e) {
var data = e.detail.data,
fileInfo = e.detail.file;
img.src = data;
}
var input = document.getElementById('inputId'),
img = document.getElementById('imgId');
input.onchange = function (e) {
loadFileFromInput(e.target,'dataurl');
};
input.addEventListener('fileLoaded',fileHandler)
Probably my code isn't as good as some users but I think you will get the point of it. Here you can see an example
Following is the working code.
<input type='file' onchange="readURL(this);" />
<img id="ShowImage" src="#" />
Javascript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#ShowImage')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
Try this
window.onload = function() {
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("uploadImage");
filesInput.addEventListener("change", function(event) {
var files = event.target.files;
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load", function(event) {
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/>";
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}
});
}
}
<input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/>
<div id="result" class="uploadPreview">
What about this solution?
Just add the data attribute "data-type=editable" to an image tag like this:
<img data-type="editable" id="companyLogo" src="http://www.coventrywebgraphicdesign.co.uk/wp-content/uploads/logo-here.jpg" height="300px" width="300px" />
And the script to your project off course...
function init() {
$("img[data-type=editable]").each(function (i, e) {
var _inputFile = $('<input/>')
.attr('type', 'file')
.attr('hidden', 'hidden')
.attr('onchange', 'readImage()')
.attr('data-image-placeholder', e.id);
$(e.parentElement).append(_inputFile);
$(e).on("click", _inputFile, triggerClick);
});
}
function triggerClick(e) {
e.data.click();
}
Element.prototype.readImage = function () {
var _inputFile = this;
if (_inputFile && _inputFile.files && _inputFile.files[0]) {
var _fileReader = new FileReader();
_fileReader.onload = function (e) {
var _imagePlaceholder = _inputFile.attributes.getNamedItem("data-image-placeholder").value;
var _img = $("#" + _imagePlaceholder);
_img.attr("src", e.target.result);
};
_fileReader.readAsDataURL(_inputFile.files[0]);
}
};
//
// IIFE - Immediately Invoked Function Expression
// https://stackoverflow.com/questions/18307078/jquery-best-practises-in-case-of-document-ready
(
function (yourcode) {
"use strict";
// The global jQuery object is passed as a parameter
yourcode(window.jQuery, window, document);
}(
function ($, window, document) {
"use strict";
// The $ is now locally scoped
$(function () {
// The DOM is ready!
init();
});
// The rest of your code goes here!
}));
See demo at JSFiddle
Preview multiple images before it is uploaded using jQuery/javascript?
This will preview multiple files as thumbnail images at a time
Html
<input id="ImageMedias" multiple="multiple" name="ImageMedias" type="file"
accept=".jfif,.jpg,.jpeg,.png,.gif" class="custom-file-input" value="">
<div id="divImageMediaPreview"></div>
Script
$("#ImageMedias").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#divImageMediaPreview");
dvPreview.html("");
$($(this)[0].files).each(function () {
var file = $(this);
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("style", "width: 150px; height:100px; padding: 10px");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
Working Demo on Codepen
Working Demo on jsfiddle
I hope this will help.
<img id="blah" alt="your image" width="100" height="100" />
<input type="file" name="photo" id="fileinput" />
<script>
$('#fileinput').change(function() {
var url = window.URL.createObjectURL(this.files[0]);
$('#blah').attr('src',url);
});
</script>
To Preview MULTIPLE Files and Single file in single function with reusable approach using Plain JavaScript
function imagePreviewFunc(that, previewerId) {
let files = that.files
previewerId.innerHTML='' // reset image preview element
for (let i = 0; i < files.length; i++) {
let imager = document.createElement("img");
imager.src = URL.createObjectURL(files[i]);
previewerId.append(imager);
}
}
<input accept="image/*" type='file' id="imageInput_1"
onchange="imagePreviewFunc(this, imagePreview_1)" />
<div id="imagePreview_1">This Div for Single Image Preview</div>
<hr />
<input class="form-control" accept="image/*" type='file' id="imageInput_2" multiple="true"
onchange="imagePreviewFunc(this, imagePreview_2)" />
<div id="imagePreview_2">This Div for Multiple Image Preview</div>
I have made a plugin which can generate the preview effect in IE 7+ thanks to the internet, but has few limitations. I put it into a github page so that its easier to get it
$(function () {
$("input[name=file1]").previewimage({
div: ".preview",
imgwidth: 180,
imgheight: 120
});
$("input[name=file2]").previewimage({
div: ".preview2",
imgwidth: 90,
imgheight: 90
});
});
.preview > div {
display: inline-block;
text-align:center;
}
.preview2 > div {
display: inline-block;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://rawgit.com/andrewng330/PreviewImage/master/preview.image.min.js"></script>
Preview
<div class="preview"></div>
Preview2
<div class="preview2"></div>
<form action="#" method="POST" enctype="multipart/form-data">
<input type="file" name="file1">
<input type="file" name="file2">
<input type="submit">
</form>
For Multiple image upload (Modification to the #IvanBaev's Solution)
function readURL(input) {
if (input.files && input.files[0]) {
var i;
for (i = 0; i < input.files.length; ++i) {
var reader = new FileReader();
reader.onload = function (e) {
$('#form1').append('<img src="'+e.target.result+'">');
}
reader.readAsDataURL(input.files[i]);
}
}
}
http://jsfiddle.net/LvsYc/12330/
Hope this helps someone.
It's my code.Support IE[6-9]、chrome 17+、firefox、Opera 11+、Maxthon3
function previewImage(fileObj, imgPreviewId) {
var allowExtention = ".jpg,.bmp,.gif,.png"; //allowed to upload file type
document.getElementById("hfAllowPicSuffix").value;
var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
var browserVersion = window.navigator.userAgent.toUpperCase();
if (allowExtention.indexOf(extention) > -1) {
if (fileObj.files) {
if (window.FileReader) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
};
reader.readAsDataURL(fileObj.files[0]);
} else if (browserVersion.indexOf("SAFARI") > -1) {
alert("don't support Safari6.0 below broswer");
}
} else if (browserVersion.indexOf("MSIE") > -1) {
if (browserVersion.indexOf("MSIE 6") > -1) {//ie6
document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
} else {//ie[7-9]
fileObj.select();
fileObj.blur();
var newPreview = document.getElementById(imgPreviewId);
newPreview.style.border = "solid 1px #eeeeee";
newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
newPreview.style.display = "block";
}
} else if (browserVersion.indexOf("FIREFOX") > -1) {//firefox
var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]);
if (firefoxVersion < 7) {//firefox7 below
document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
} else {//firefox7.0+ 
document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
}
} else {
document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
}
} else {
alert("only support" + allowExtention + "suffix");
fileObj.value = ""; //clear Selected file
if (browserVersion.indexOf("MSIE") > -1) {
fileObj.select();
document.selection.clear();
}
}
}
function changeFile(elem) {
//file object , preview img tag id
previewImage(elem,'imagePreview')
}
<input type="file" id="netBarBig" onchange="changeFile(this)" />
<img src="" id="imagePreview" style="width:120px;height:80px;" alt=""/>
Default Iamge
#Html.TextBoxFor(x => x.productModels.DefaultImage, new {#type = "file", #class = "form-control", onchange = "openFile(event)", #name = "DefaultImage", #id = "DefaultImage" })
#Html.ValidationMessageFor(model => model.productModels.DefaultImage, "", new { #class = "text-danger" })
<img src="~/img/ApHandler.png" style="height:125px; width:125px" id="DefaultImagePreview"/>
</div>
<script>
var openFile = function (event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function () {
var dataURL = reader.result;
var output = document.getElementById('DefaultImagePreview');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
</script>
Here's a solution if you're using React:
import * as React from 'react'
import { useDropzone } from 'react-dropzone'
function imageDropper() {
const [imageUrl, setImageUrl] = React.useState()
const [imageFile, setImageFile] = React.useState()
const onDrop = React.useCallback(
acceptedFiles => {
const file = acceptedFiles[0]
setImageFile(file)
// convert file to data: url
const reader = new FileReader()
reader.addEventListener('load', () => setImageUrl(String(reader.result)), false)
reader.readAsDataURL(file)
},
[setImageFile, setImageUrl]
)
const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop })
return (
<div>
<div {...getRootProps()}>
{imageFile ? imageFile.name : ''}
{isDragActive ? <p>Drop files here...</p> : <p>Select image file...</p>}
<input {...getInputProps()} />
</div>
{imageUrl && (
<div>
Your image: <img src={imageUrl} />
</div>
)}
</div>
)
}
https://stackoverflow.com/a/59985954/8784402
ES2017 Way
// convert file to a base64 url
const readURL = file => {
return new Promise((res, rej) => {
const reader = new FileReader();
reader.onload = e => res(e.target.result);
reader.onerror = e => rej(e);
reader.readAsDataURL(file);
});
};
// for demo
const fileInput = document.createElement('input');
fileInput.type = 'file';
const img = document.createElement('img');
img.attributeStyleMap.set('max-width', '320px');
document.body.appendChild(fileInput);
document.body.appendChild(img);
const preview = async event => {
const file = event.target.files[0];
const url = await readURL(file);
img.src = url;
};
fileInput.addEventListener('change', preview);
Here is a much easy way to preview image before upload using pure javascript;
//profile_change is the id of the input field where we choose an image
document.getElementById("profile_change").addEventListener("change", function() {
//Here we select the first file among the selected files.
const file = this.files[0];
/*here i used a label for the input field which is an image and this image will
represent the photo selected and profile_label is the id of this label */
const profile_label = document.getElementById("profile_label");
//Here we check if a file is selected
if(file) {
//Here we bring in the FileReader which reads the file info.
const reader = new FileReader();
/*After reader loads we change the src attribute of the label to the url of the
new image selected*/
reader.addEventListener("load", function() {
dp_label.setAttribute("src", this.result);
})
/*Here we are reading the file as a url i.e, we try to get the location of the
file to set that as the src of the label which we did above*/
reader.readAsDataURL(file);
}else {
//Here we simply set the src as default, whatever you want if no file is selected.
dp_label.setAttribute("src", "as_you_want")
}
});
And here is the HTML;
<label for="profile_change">
<img title="Change Profile Photo" id="profile_label"
src="as_you_want" alt="DP" style="height: 150px; width: 150px;
border-radius: 50%;" >
</label>
<input style="display: none;" id="profile_change" name="DP" type="file" class="detail form-control">
for my app, with encryped GET url parameters, only this worked. I always got a TypeError: $(...) is null.
Taken from https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
function assignFilePreviews() {
$('input[data-previewable=\"true\"]').change(function() {
var prvCnt = $(this).attr('data-preview-container');
if (prvCnt) {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
var img = $('<img>');
img.attr('src', e.target.result);
img.error(function() {
$(prvCnt).html('');
});
$(prvCnt).html('');
img.appendTo(prvCnt);
}
reader.readAsDataURL(this.files[0]);
}
}
});
}
$(document).ready(function() {
assignFilePreviews();
});
HTML
<input type="file" data-previewable="true" data-preview-container=".prd-img-prv" />
<div class = "prd-img-prv"></div>
This also handles case when file with invalid type ( ex. pdf ) is choosen

Downloading multiple files from the Google Drive by one action on google app script

I have list of URL links on my google app script html page. I have a download button. When I click the download button, I want to download all files from my google drive to my computer using the URL links.
To start with:
I tried for one link to put it in a folder on my google drive. But it doesn't work.
I have shared the spreadsheet file in public domain here https://docs.google.com/spreadsheets/d/1sXWWAdfEIJSj9_QPBjkR6CKhd4bzrYIMa4hImipySWI/edit?usp=sharing
The web link: https://script.google.com/macros/s/AKfycbwkBfuZzSDV5UgQLugJoWXH-2pDrtqsd2Ph5HAkx_oFOvR6gD0/exec
please search for a name "sam"
Would you help me please?
Thank you.
// Start html part
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<p>Enter the name: sam </p>
<div>
<form id="searchform">
<input name="nameperson" type="text">
<input type="submit" value="search">
</form>
</div>
<div id="result">
</div>
<div id="download" hidden="true">
<button> download </button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$("#searchform").submit(function(){
google.script.run.withSuccessHandler(function(valreturn){
var response=JSON.parse(valreturn);
var newHTML=[];
newHTML.push('<table>' + '<tr>' +'<th>'+"Name"+'</th>'+
'<th>'+"URL"+'</th>'+ '<tr>');
for( var i=response.length-1; i >= 0 ; i--){
newHTML.push('<tr>' + '<td>' + response[i].name + '</td>' +
'<td>' + '<a href= " ' + response[i].url + ' " target="_blank" >' + "url" + '</a>' + '</td>' + '</tr>');
}
$("#result").html(newHTML.join(""));
$("#download").show();
}).seachRecord(this);
});
$("#download").click(function() {
alert("how can I download these files ?");
});
});
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
</script>
</body>
</html>
//end html
function getFilepdf() {
var fileURL="https://drive.google.com/file/d/0BybO_Qe9EIRKZExPSWJJXzl1ajQ/view";
var response = UrlFetchApp.fetch(fileURL);
var fileBlob = response.getBlob();
fileuploadpdf(fileBlob);
}
function fileuploadpdf(filedata){
try {
var dropbox = "stackflowfolder";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = filedata;
var file = folder.createFile(blob);
} catch (error) {
return error.toString(); }
}

return undefined on div

Here i'm attempting to load a form using ajax and set to "maindiv" upon clicking a button "Add Item".but returns undefined. A servlet named "AddItem" also exists..
html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type="button" onclick="loadAddItemForm()" value="Add Item"/>
<div id="maindiv"> </div>
<script>
function loadAddItemForm() {
var x;
if (window.XMLHttpRequest) {
x = new XMLHttpRequest();
}
x.onreadystatechange = function () {
if (x.readyState == 4 && x.status == 200) {
//
var txt = "ItemCode:" + "<input type='text' id='itemcodetxt'><br>" + "ItemName:" + "<input type='text' id='itemnametxt'><br>" + "Description:" + "<input type='text' id='descriptiontxt'><br>" + "QtyOnHand:" + "<input type='text' id='qtyonhandtxt'><br>" + "Reorderlevel:" + "<input type='text' id='reorderleveltxt'><br>" + "Unit price:" + "<input type='text' id='unitpricetxt'><br><input type='button' value='Add' onclick='addItem()'/>";
}
document.getElementById("maindiv").innerHTML = txt;
};
x.open("GET", "AddItem", true);
x.send();
}
</script>
</body>
You're not passing in the page, try
x.open("GET", "AddItem.html", true);
assuming that's the page you waant to open.
it's returning false because it's looking for AddItem, and as it's returning false the txt is undefined as the if block isn't executed

Cannot get treemap to render with new JSON data

I am using the d3.js treemap in a an application with backbone.js. The treemap renders correctly with the first JSOn data, but subsequent calls with different JSON data do not cause the treemap to re-render.
My HTML looks like this:
<html>
<head>
<title>Jenkins analytics</title>
<!-- stylesheets -->
<link rel="stylesheet" href="css/spa.css" type="text/css"/>
<link rel="stylesheet" href="css/treemap.css" type="text/css"/>
</head>
<body>
<nav>
<form>
<fieldset>
<label for="chart">Chart:</label>
<select id="chart" name="chart">
<option value="treemap" selected>Treemap</option>
<option value="motion">MotionChart</option>
</select>
</fieldset>
</form>
<form>
<fieldset>
<label for="period">Period:</label>
<select id="period" name="period">
<option value="lastday" selected>Day</option>
<option value="lastweek">Week</option>
<option value="lastmonth">Month</option>
</select>
<label for="team">Team:</label>
<select id="team" name="team">
<option value="all" selected>all</option>
<option value="spg">spg</option>
<option value="beacon">beacon</option>
<option value="disco">disco</option>
</select>
<label for="status">Status:</label>
<select id="status" name="status">
<option value="" selected>all</option>
<option value="SUCCESS">success</option>
<option value="FAILURE">failure</option>
<option value="ABORTED">aborted</option>
</select>
</fieldset>
</form>
<form>
<fieldset>
<label for="duration">Duration</label>
<input id="duration" type="radio" name="mode" value="size" checked />
<label for="count">Count</label>
<input id="count" type="radio" name="mode" value="count" />
<label for="average">Average</label>
<input id="average" type="radio" name="mode" value="avg" />
</fieldset>
</form>
</nav>
<div id="container" />
<!-- Third party javascript -->
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js" charset="utf-8"></script>
<script type="text/javascript" src="script/underscore/underscore.js" charset="utf-8"></script>
<script type="text/javascript" src="script/backbone/backbone.js" charset="utf-8"></script>
<script type="text/javascript" src="script/d3/d3.v3.js" charset="utf-8"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<!-- Application javascript -->
<script type="text/javascript" src="script/module.js"></script>
<!-- Startup -->
<script>
var navview = new NavViewer();
</script>
</body>
</html>
script/module.js looks like this:
var NavViewer = Backbone.View.extend({
el: 'nav',
events: {
"change #chart": "change_chart",
"change #period": "change_period",
"change #team": "change_team",
"change #status": "change_status"
},
initialize: function() {
console.log("NavViewer.initialize");
this.d3view = new D3Viewer();
this.active_view = this.d3view;
},
change_chart: function(e) {
console.log("NavViewer.change_chart");
},
change_period: function(e) {
var _period = $('#period').val();
console.log("NavViewer.change_period to " + _period);
this.active_view.load();
},
change_team: function(e) {
var _team = $('#team').val();
console.log("NavViewer.change_team to "+ _team);
this.active_view.load();
},
change_status: function(e) {
var _status = $('#status').val();
console.log("NavViewer.change_status to " + _status);
this.active_view.load();
}
});
var JenkinsViewer = Backbone.View.extend({
el: '#container',
server: "http://192.168.1.100:5000",
url_fragment: function() {
var _period = $('#period').val();
var _team = $('#team').val();
var _status = $('#status').val();
return "when=" + _period +
(_team == "all" ? "" : ("&" + "team=" + _team)) +
(_status == "" ? "" : ("&" + "status=" + _status));
}
});
var D3Viewer = JenkinsViewer.extend({
initialize: function() {
this.margin = {top: 8, right: 0, bottom: 0, left: 0};
this.width = 1200 - this.margin.left - this.margin.right;
this.height = 800 - this.margin.top - this.margin.bottom - 60;
this.container = d3.select(this.el);
this.color = d3.scale.category20c();
this.base_url = this.server + "/team_build";
this.treemap = d3.layout.treemap()
.size([this.width, this.height])
.sticky(true)
.value(function(d) { return d.size; });
this.position = function() {
this.style("left", function(d) { return d.x + "px"; })
.style("top", function(d) { return d.y + "px"; })
.style("width", function(d) { return Math.max(0, d.dx - 1) + "px"; })
.style("height", function(d) { return Math.max(0, d.dy - 1) + "px"; });
};
/* style the container */
this.container
.style("position", "relative")
.style("width", this.width + "px")
.style("height", this.height + "px")
.style("left", this.margin.left + "px")
.style("top", this.margin.top + "px")
.style("border", "1px solid black");
/* tootlip is appended to container */
this.tooltip = this.container.append("div")
.attr('class', 'tooltip')
.style("visibility", "hidden")
.style("background-color", "#ffffff");
this.load();
},
load: function() {
var $container = this.container;
var color = this.color;
var treemap = this.treemap;
var position = this.position;
var tooltip = this.tooltip;
var url = this.base_url + "?" + this.url_fragment();
console.log("D3View.load: " + url);
d3.json(url, function(error, root) {
/* 'root' actually means the data retrieved by the xhr call */
var node = $container.datum(root)
.selectAll(".node")
.data(treemap.nodes);
node.enter().append("div")
.attr("class", "node")
.call(position)
.style("background", function(d) { return d.children ? color(d.name) : null; })
.text(function(d) { return d.children ? null : d.name; })
.on("mouseover", function(d) {
tooltip.html(d.name + ": " + Math.floor(d.value))
.style("visibility", "visible");
this.style.cursor = "hand";
})
.on("mouseout", function(){
tooltip.style("visibility", "hidden");
});
d3.selectAll("input").on("change", function change() {
var functions = {
count: function(d) { return d.count; },
size: function(d) { return d.size; },
avg: function(d) { return d.size / d.count; }
};
var value = functions[this.value];
node
.data(treemap.value(value).nodes)
.transition()
.duration(1500)
.call(position);
});
});
return true;
}
});
Here are things I've done:
read the d3.js code for d3.json and d3.layout.treemap
googled the living daylights out of this
read Lars Kotthoff's d3.js answers on StackOverflow
read some articles: Enter and Exit, D3.js: How to handle dynamic JSON Data
tried treemap.sticky(false)
tried adding node.exit().remove()
I think the problem might relate to stickiness or the absence of a call node.exit().remove(). I've tried modifying both of those without success. However, to get the interactive clientside UI, I think I need to use treemap.sticky(true).
I've confirmed that I get different JSON each time I hit the REST API service. I've confirmed that container.datum().children changes in size between calls, confirming for me that it is a question of treemap not re-rendering.
D3.js: How to handle dynamic JSON Data looks highly relevant:
"It's worth mentioning that if you already have data with the same key, d3.js will store the data in the node but will still use the original data."
"When I started playing with d3.js, I thought that rendered data would be evented and react to my changing of scales, domains and whatnot. It's not. You have to tell d3.js to update the current stuff or it will stay there, unsynced."
"I assign the result of data() to a variable because enter() only affects new data that are not bound to nodes."
Here is what I ended up doing in my load method:
load: function() {
var $container = this.container;
var color = this.color;
var treemap = this.treemap;
var position = this.position;
var tooltip = this.tooltip;
var url = this.base_url + "?" + this.url_fragment();
console.log("D3View.load: " + url);
d3.json(url, function(error, root) {
var tooltip_mouseover = function(d) {
tooltip.html(d.name + ": " + Math.floor(d.value))
.style("visibility", "visible");
this.style.cursor = "hand";
};
var tooltip_mouseout = function(){
tooltip.style("visibility", "hidden");
};
var background_color = function(d) { return d.children ? color(d.name) : null; };
var text_format = function(d) { return d.children ? null : d.name; };
/*
* Refresh sticky bit
* https://github.com/mbostock/d3/wiki/Treemap-Layout
* "Implementation note: sticky treemaps cache the array of nodes internally; therefore, it
* is not possible to reuse the same layout instance on multiple datasets. To reset the
* cached state when switching datasets with a sticky layout, call sticky(true) again."
*/
treemap.sticky(true);
/* 'root' actually means the data retrieved by the xhr call */
var nodes = $container.datum(root)
.selectAll(".node")
.data(treemap.nodes);
var enter = nodes.enter().append("div")
.attr("class", "node")
.call(position)
.style("background", background_color)
.text(text_format)
.on("mouseover", tooltip_mouseover)
.on("mouseout", tooltip_mouseout);
var exit = nodes.exit().remove();
var update = nodes.style("background", background_color)
.call(position)
.text(text_format);
d3.selectAll("input").on("change", function change() {
var functions = {
count: function(d) { return d.count; },
size: function(d) { return d.size; },
avg: function(d) { return d.size / d.count; }
};
var value = functions[this.value];
$container.selectAll(".node")
.data(treemap.value(value).nodes)
.transition()
.duration(1500)
.call(position);
});
});
There are two important changes:
Reset treemap sticky bit
Use enter/exit/update selections for new/missing/changed nodes/data
Notice also that enter nodes have the side effect of adding a div of class node and the exit and update nodes do not reference that div-class -- except they do, in the creation of nodes. If add a further selection on node-class in those places, your selection will be empty and the exit and update code will be no-ops.
Thanks to AmeliaBR for posting a really helpful comment with a link to an SO answer she composed.
Other helpful reads:
https://github.com/mbostock/d3/wiki/Selections
http://bost.ocks.org/mike/join/