selecting pictures in html javascript jquery - javascript

i create a form in asp.netcore mvc where i upload the pictures i want that when i hit choose button i select picuture or group of picture after that if i hit again the choose button i again select picture or group of picuture but it do not replace the pictures which i select before.
my html and javascript form
<div class="row">
<input type="file" name="imge1" id="file" asp-for="imge1" class="hidden" multiple>
<button type="button" class="btn btn-primary" id="filebutton"><span id="filetext">Select File</span></button>
<div id="preview" style="column-gap: 25px;"></div>
</div>
<div id="image_preview"></div>
<script>
$(document).ready(function () {
$('#filebutton').click(function () {
$('#file').click();
});
$('#file').change(function () {
var name = $(this).val().split('\\').pop();
var file = $(this)[0].files;
if (name != '') {
if (file.length >= 2) {
$('#filetext').html(file.length + ' files ready to upload');
}
else {
$('#filetext').html(name);
}
}
});
$('#file').on("change", previewImages);
});
function previewImages() {
var $preview = $('#preview').empty();
if (this.files) $.each(this.files, readAndPreview);
function readAndPreview(i, file) {
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
$(reader).on("load", function () {
$preview.append($("<img>", { src: this.result, height: 80, }));
});
reader.readAsDataURL(file);
}
}
</script>

You mentioned that,
it works but when i post it just take those picture which i select
after first select means it replace the previous selected picture the
previous pictures not added in imge1
It looks like this is the expected behavior.
When you select the images for the first time, it will show you the list of files when you hover over the File Input.
When you again click the button to add new images, the File Input control will remove the previous list of images and show you the latest selected images.
This is how File Input control works.
Further, due to security reasons, it is not possible to append the files to the previously selected files of the File Input using JS code.

Related

Angular upload image and display to user

Id like to implement a UI where the user selects an image and that image is instantly displayed back to them for review. The user would have to click "submit" to upload/save the image to their profile.
I am having issues with the "instantly display back to the user part".
I am using angular FormData with the following markup & controller:
MARKUP
<input id="chooseFile" type="file" file-model="picFile" />
<img src="{{uploadedImage}}" /> <!-- this populates with filename but what is the path?? -->
CONTROLLER
angular.element('#chooseFile').change(function(){
var file = $scope.picFile; // this comes up "undefined" since file is still uploading when this is fired
$scope.uploadedImage = file.name;
});
I have 2 primary issues with the above code (described in comments):
1) In the controller, file comes up undefined obviously because even the smallest file takes >0s to upload while the callback is fired pretty much instantaneously. I got it work using $timeout but thats a bit of a lame hack. How can I have the callback wait until the file is uploaded??
2) The idea is to upload the file and display it in the img tag using Angular's data-binding. This works in that src is populated with the filename, but what is the path of the img. Some temporary location in cache or something?? Obviously I havent set a path to move the file yet.
Any help appreciated!
I also needed this feature, some how I manage to display image instantly.
angular.module('HelloWorldApp', [])
.controller('HelloWorldController', function($scope) {
$scope.uploadavtar = function(files) {
//var fd = new FormData();
//Take the first selected file
//fd.append("file", files[0]);
var imagefile = document.querySelector('#file');
if (imagefile.files && imagefile.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#temp_image')
.attr('src', e.target.result);
};
reader.readAsDataURL(imagefile.files[0]);
this.imagefile = imagefile.files[0];
}else{
console.log("Image not selected");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="HelloWorldApp">
<div ng-controller="HelloWorldController">
<input type="file" id="file" onchange="angular.element(this).scope().uploadavtar(this.files)"/>
</div>
<img src="" id="temp_image" width="100">
<div>
</div>
</div>
I was using laravel + Angularjs so another related post to store image is : https://stackoverflow.com/a/34830307/2815635

Retrieve image data from file input without a server

For context, I'm trying to create a "click image" file uploader. Initially there is a default image, which I then click. I trigger a file upload, and the user picks an image file they want. Then I will set the image to replace the default (and do other things with it later). Right now, the front end looks something like this:
<div class="right-preview">
<input type="image" src="img/logo.png" height="240px" width="240px" ng-click="uploadImage('right-image')" id="upload-right-image"/>
<input type="file" id="upload-right" style="visibility: hidden">
</div>
When the image is clicked, it triggers an upload action.
$scope.uploadImage = function(side) {
$image = $('#upload-' + side);
$fileInput = $('#upload-right');
$fileInput.change(function(changeEvent) {
var files = changeEvent.target.files;
for(var i = 0; i < files.length; i++) {
file = files[i];
console.log(file);
}
});
$fileInput.trigger('click');
}
When the change event is fired after the user finishes picking their file, I have the changeEvent and I know they've selected their file. Each of the files has some properties (like name and size) but I'm not seeing anything for accessing the raw data so I can set the src on my other element.
Am I just completely missing how to get the image data, or is there a better way to do this? I have no server (right now) to post this to. Perhaps there is a better way to approach this?
This link may be helpful to you - https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
I took one method from that page and added some additional functionality to hide the file upload button and have the image placeholder trigger its click event.
$('#placeholder').click(function() {
$('#img-upload').trigger('click');
});
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);
}
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img width="250" height="250" id="placeholder" src="http://place-hold.it/250x250&text='click to upload'">
<input class="hidden" type="file" onchange="previewFile()" id="img-upload">

Display & push Multiple image using javascript & html

im basic developer just wanted to push images one after other when an new image is been selected by user ,
following is my javascript :-
preview.js
<script language="javascript" type="text/javascript">
$(function () {
$("#fileupload").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#dvPreview");
dvPreview.html("");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("style", "height: 100px; width: 100px; margin-top: 20px;");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
dvPreview.html("");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
});
</script>
Html
Index.html
<div id='file'>
<label for="fileupload" style="margin-right:5px;">Group Image/Logo</label><br>
<input id="fileupload" type="file" multiple="multiple"/>
<div id="dvPreview">
</div>
</div>
This code displays the image perfectly , but only in single instance( thumbnail gets changed every time he selects an image) .
What is neccessary to just push & show the thumbnail of all the images that user wants to upload ? .
Searching google , Points which can be usefull :-
using Array &
using foreach loop
Any one can explain the proper syntax ? It would be great . Thank you .
JSFIDDLE

How to make the code workable for more than one file file object in following scenario?

I've a form containing four file controls. They may get increase and decrease in number depending on user's choice. But at least one of them will remain on a form.
I want to display the image thumbnail of the image selected by user for upload for each of these file controls.
I'm able to display the thumbnail image for one file control but not able to make it workable for more than one file control on a form.
The HTML form code is as below :
<form action="add.php" role="form" method="post" enctype="multipart/form-data">
<img src="http://localhost/prj/img/abc.jpeg" width="80" height="80">
<input type="file" name="product_image[1]" id="product_image_1">
<img src="http://localhost/prj/img/def.jpeg" width="80" height="80">
<input type="file" name="product_image[2]" id="product_image_2">
<img src="http://localhost/prj/img/lmn.jpeg" width="80" height="80">
<input type="file" name="product_image[3]" id="product_image_3">
<img src="http://localhost/prj/img/pqr.jpeg" width="80" height="80">
<input type="file" name="product_image[4]" id="product_image_4">
.
.
.
.
.
and could be so on
</form>
The jquery code which worked for me for only one file control is as follows:
HTML code is :
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" width="80" height="80"/>
</form>
jQuery code :
$(document).ready(function() {
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function() {
readURL(this);
});
});
js Fiddle link is : http://jsfiddle.net/LvsYc/
The above code worked really very fine for me when there is only one such file field.
But not able to make the same thing workable for a form when there could be more than one such file controls are present.
Can someone please help me in this regard?
Thanks for spending some of your valuable time in understanding my issue. Waiting for your precious replies.
If you want any information regarding my question please do let me know.
Probably my answer to this question will help:
$.fn.checkFileType = function (options) {
var defaults = {
allowedExtensions: [],
preview: "",
success: function () {},
error: function () {}
};
options = $.extend(defaults, options);
$previews = $(options.preview);
return this.each(function (i) {
$(this).on('change', function () {
var value = $(this).val(),
file = value.toLowerCase(),
extension = file.substring(file.lastIndexOf('.') + 1),
$preview = $previews.eq(i);
if ($.inArray(extension, options.allowedExtensions) == -1) {
options.error();
$(this).focus();
} else {
if (this.files && this.files[0] && $preview) {
var reader = new FileReader();
reader.onload = function (e) {
$preview.show().attr('src', e.target.result);
options.success();
};
reader.readAsDataURL(this.files[0]);
} else {
options.error();
}
}
});
});
};
You can use the above function as follows:
$('.fileUpload').checkFileType({ // where fileUpload is the common class given for file upload elements
allowedExtensions: ['jpg', 'jpeg',"gif"], // allowed extensions
preview: ".preview", // where .preview is the common class given for file upload elements
success: function () {
alert('success')
},
error: function () {
alert('Error');
}
});
The image will be set as the src of element at the index of your <input> among the set of elements matched by the jQuery selector specified in preview option.
Demo

HTML5 Drag & Drop File Upload gets JavaScript 'permission denied' accessing FileInfo object

I'm trying to upload a single file using standard multipart upload. It should work just as if there was a form on the page with a file field and a text field and a submit button at the bottom. They identify the file, type in a few other strings and click the "upload" button. In this case, though the form is just a dummy used to create a FileForm object. And the text field and file field and drop box are just random DOM elements with JS behind them. (HTML and jQuery/JavaScript below.)
So, concerning the non-form code, it works (meaning the file uploads and I can see the bytes on the server) only if the user uses the <input type="file" .../> element to identify the file.
If the user does a drag and drop of a file onto a spot on the page, I save the file info in a data element and use it from there instead of from the file input field. But when a file is dropped, an error (shown below) occurs because the code isn't allowed to get a single file out of the FileList returned by the drop.
So I put all the relevant code here and set up a fiddle. But, when I strip it down to the jsFiddle (linked below), both methods work.
That truly messes up the whole question. But I'm going to submit it anyway because it has code pulled together and simplified from a lot of older SO questions for doing file uploads and drag & drop. Plus someone might know what could cause the error.
Question: What sorts of things should I look for on my full page that would cause the contents of the dropped FileInfo object to become protected? That's the question for now.
Here's the FIDDLE
Here's the error message:
Error: Permission denied to access property 'length'
if (files.length > 1) {
Here's the HTML
<label for="dropbox">
<span>DROP HERE:</span>
<!-- CSS makes this a big purple bordered box -->
<div id="dropbox"> </div>
<div id="dropfile"></div>
</label>
<label for="inputFile">
<span>FILES:</span>
<input type="file" id="inputFile" name="inputFile"/>
</label>
<input type="button" id="upload" value="Upload"/>
<form enctype="multipart/form-data" method="post" id="fileform"></form>
Here's the JS w/ jQuery
$.event.props.push('dataTransfer');
$("#dropbox").on("drop", function(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.originalEvent.dataTransfer;
var files = dt.files;
// errors on these lines *******************************************
if (files.length > 1) { alert(files.length + " files dropped. Only 1 allowed"); }
var file = files[0];
// errors on these lines *******************************************
$("#dropfile").text(file.name);
$("#dropbox").data("file", file);
try {
$("#inputFile").val(""); // works in some browsers
} catch (e) {
// ignore failure in some browsers
}
});
$("#dropbox").on("dragenter", function(e) {
e.stopPropagation();
e.preventDefault();
});
$("#dropbox").on("dragover", function(e) {
e.stopPropagation();
e.preventDefault();
});
$("#inputFile").change(function(e) { // selecting a file, erases dropped one
$("#dropfile").text("");
$("#dropbox").removeData("file");
});
$("#upload").click(function() {
var data = new FormData($("#fileform")[0]);
var obj = readTextBoxes();
for (var prop in obj) {
data.append(prop, obj[prop]);
}
// HTML file input user's choice(s)...
var dropfile = $("#dropbox").data("file");
if (dropfile) {
data.append("inputFile", dropfile);
} else {
$.each($("#inputFile")[0].files, function(i, file) {
data.append("inputFile[" + i + "]", file);
});
}
var parms = {
url : baseUrl + "v2/document/upload",
type : "POST",
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
data : data,
timeout : 40000
};
var promise = $.ajax(parms);
// ... handle response
});

Categories