ajax image upload with pre-preview - javascript

I am uploading image with ajax and showing image before uploading with jquery.
here is my html code
<form id="uploadimageS2" action="" method="post" enctype="multipart/form-data">
<div id="image_previewS2"><img id="previewingS2" src="img/noimage.png" /></div>
<div id="selectImageS2">
<label>Select Your Image</label><br/>
<input type="file" name="fileS2" id="fileS2" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
then here is my jquery code
// Function to preview image
$("#fileS2").change(function() {
$("#messageS2").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#previewingS2').attr('src','img/noimage.png');
$("#messageS2").html("<p id='errormsg'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
function imageIsLoaded(e) {
$('#image_previewS2').css("display", "block");
$('#previewingS2').attr('src', e.target.result);
$('#previewingS2').attr('width', '250px');
$('#previewingS2').attr('height', '230px');
};
reader.readAsDataURL(this.files[0]);
var file = this.files[0];
here i want to add another element instead of "this". because i am uploading 3 images in one page and when using this script it is going wired.
i already tried
reader.readAsDataURL($(#uploadimageS2).files[0]);
reader.readAsDataURL($(#fileS2).files[0]);
and those didn't work.

Related

How to retrive save image in image preview in edit form?

I am trying to use image preview before upload.Its working fine while creating new.but how to retrieve that image that has already saved in edit form and can be change when i try to change another image ? This is my input type for file.
<input type="file" class="form-control" name="image" id="image">
<img id="user_image" src="{asset('admin/images/user/'.auth()->user()->image)}}" />
This is my script file to preview image before uploading
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
#php $value=auth()->user()->image; #endphp
$('#user_image').show();
$('#user_image').attr('src', e.target.result).slideDown();;
};
reader.readAsDataURL(input.files[0]);
}
}
$("#image").change(function() {
readURL(this);
});
</script>

input "submit" does not upload files when using onsubmit attribute

In this snippet onsubmit is used to display the image uploaded and to keep it visible return false; is used.
<form method="POST" enctype="multipart/form-data" onsubmit="display();return false;">
<input type="file" name="file" id="file">
<input type="submit" value="Upload">
</form>
JavaScript:
function display() {
var file = document.getElementById('file').files[0];
var reader = new FileReader();
// it's onload event and you forgot (parameters)
reader.onload = function(e) {
// the result image data
document.getElementById("img").src = e.target.result;
}
// you have to declare the file loading
reader.readAsDataURL(file);
}
When doing so, the image loads and is displayed but does not upload to the directory of uploads specified.
How can I upload the actual images and show the image without the need of page refresh?
Rather than changing the img after submission or manipulating a submit button I found that it's better to just use this:
<input type="file" name="file" id="file" onchange="preview_image(event)">
And then in js simply read it onchange
function preview_image(event) {
var reader = new FileReader();
reader.onload = function() {
document.getElementById('img').src = reader.result;
}
reader.readAsDataURL(event.target.files[0]);
}

how to prevent input type file from accepting some inputs on change function

I'm working on a project and I need the user to upload only pdf files.
I'm trying to do this in the front-end so whenever the input detects a file type that is not a pdf should reject it. Everything seems correct. However, when I hover over the input it shows me that the wrong file is uploaded. So what should I do?
function changeName(elem) {
$("input[type='file']").
elem.on("change", function() {
var fileName = elem.val().split("\\").pop();
var fileExtension = elem.val().split(".").pop();
if (fileExtension === "pdf") {
elem.siblings(".Syllabus").text(fileName);
} else {
elem.siblings(".Syllabus").val('');
elem.siblings(".Syllabus").text('...');
alert('Only PDF files are accepted');
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="Syllabus fileReset">...</label>
<input type="file" accept="application/pdf" name="file1" onClick="changeName($(this));" required class="upload-button removable" />
This code works better than what you posted
$("input[type='file']").on("change", function(e) {
var elem = $(this);
elem.siblings(".Syllabus").text("...")
var fileName = elem.val().split("\\").pop();
var fileExtension = elem.val().split(".").pop();
if (fileExtension !== "pdf") {
elem.siblings(".Syllabus").text('Only PDF files are accepted')
elem.replaceWith(elem.val('').clone(true));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="Syllabus fileReset">...</label>
<input type="file" accept="application/pdf" name="file1" required class="upload-button removable" />

Replace uploaded image with placeholder image permanently

I've been trying to give functionality of replacing image with my uploaded placeholder image so that my client's don't need to login at the backend of (any CMS) and almost all of them are non-techies.
The following piece of code below will display the placeholder image along with the "upload file button". Once they upload their image, I will delete the choose file option. Is there any possibility of storing their uploaded image somewhere in the folder of the website?
HTML:
<input type='button' id='remove' value='remove' class='hide'/>
<input type='file' id="imgInp" /><br>
<img width="230px" id="blah" src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/No_pub.svg/150px-No_pub.svg.png" alt="your image" />
JS:
$('#blah').show();
$('#remove').hide();
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(){
if( $('#imgInp').val()!=""){
$('#remove').show();
$('#blah').show('slow');
}
else {
$('#remove').hide();
$('#blah').hide('slow');
}
readURL(this);
});
$('#remove').click(function(){
$('#imgInp').val('');
$(this).hide();
$('#blah').hide('slow');
$('#blah').attr('src','http://upload.wikimedia.org/wikipedia/commons/thumb/4/40/No_pub.svg/150px-No_pub.svg.png');
});
Check out here JSFIDDLE
try using this
<input id="src" type="file"/>
<input type="button" id="rem" value="remove" style="visibility:hidden;" onclick="myfun()">
<img id="target" src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/No_pub.svg/150px-No_pub.svg.png" style="width:100px;height:100px;"/>
<script>
function showImage(src,target) {
var fr=new FileReader();
fr.onload = function(e) { target.src = this.result; };
src.addEventListener("change",function() {
fr.readAsDataURL(src.files[0]);
document.getElementById("src").style.visibility = "hidden";
document.getElementById("rem").style.visibility = "visible";
});
}
var src = document.getElementById("src");
var target = document.getElementById("target");
showImage(src,target);
function myfun(){
target.src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/No_pub.svg/150px-No_pub.svg.png";
document.getElementById("src").style.visibility = "visible";
document.getElementById("rem").style.visibility = "hidden";
};
</script>

Acces a file in a file upload input [duplicate]

I actually have a file input and I would like to retrieve the Base64 data of the file.
I tried:
$('input#myInput')[0].files[0]
to retrieve the data. But it only provides the name, the length, the content type but not the data itself.
I actually need these data to send them to Amazon S3
I already test the API and when I send the data through html form with encode type "multipart/form-data" it works.
I use this plugin : http://jasny.github.com/bootstrap/javascript.html#fileupload
And this plugins gives me a preview of the picture and I retrieve data in the src attribute of the image preview. But when I send these data to S3 it does not work. I maybe need to encode the data like "multipart/form-data" but I don't know why.
Is there a way to retrieve these data without using an html form?
input file element:
<input type="file" id="fileinput" />
get file :
var myFile = $('#fileinput').prop('files');
You can try the FileReader API. Do something like this:
<!DOCTYPE html>
<html>
<head>
<script>
function handleFileSelect()
{
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('The File APIs are not fully supported in this browser.');
return;
}
var input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
var file = input.files[0];
var fr = new FileReader();
fr.onload = receivedText;
//fr.readAsText(file);
//fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
fr.readAsDataURL(file);
}
}
function receivedText() {
document.getElementById('editor').appendChild(document.createTextNode(fr.result));
}
</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
<div id="editor"></div>
</body>
</html>
I created a form data object and appended the file:
var form = new FormData();
form.append("video", $("#fileInput")[0].files[0]);
and i got:
------WebKitFormBoundaryNczYRonipfsmaBOK
Content-Disposition: form-data; name="video"; filename="Wildlife.wmv"
Content-Type: video/x-ms-wmv
in the headers sent. I can confirm this works because my file was sent and stored in a folder on my server. If you don't know how to use the FormData object there is some documentation online, but not much. Form Data Object Explination by Mozilla
Html:
<input type="file" name="input-file" id="input-file">
jQuery:
var fileToUpload = $('#input-file').prop('files')[0];
We want to get first element only, because prop('files') returns array.
input element, of type file
<input id="fileInput" type="file" />
On your input change use the FileReader object and read your input file property:
$('#fileInput').on('change', function () {
var fileReader = new FileReader();
fileReader.onload = function () {
var data = fileReader.result; // data <-- in this var you have the file data in Base64 format
};
fileReader.readAsDataURL($('#fileInput').prop('files')[0]);
});
FileReader will load your file and in fileReader.result you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)
FileReader API with jQuery, simple example.
( function ( $ ) {
// Add click event handler to button
$( '#load-file' ).click( function () {
if ( ! window.FileReader ) {
return alert( 'FileReader API is not supported by your browser.' );
}
var $i = $( '#file' ), // Put file input ID here
input = $i[0]; // Getting the element from jQuery
if ( input.files && input.files[0] ) {
file = input.files[0]; // The file
fr = new FileReader(); // FileReader instance
fr.onload = function () {
// Do stuff on onload, use fr.result for contents of file
$( '#file-content' ).append( $( '<div/>' ).html( fr.result ) )
};
//fr.readAsText( file );
fr.readAsDataURL( file );
} else {
// Handle errors here
alert( "File not selected or browser incompatible." )
}
} );
} )( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" />
<input type='button' id='load-file' value='Load'>
<div id="file-content"></div>
To read as text... uncomment //fr.readAsText(file); line and comment fr.readAsDataURL(file);
Get file using jquery
element html:
<input id="fileInput" type="file" />
jquery code:
$("#fileInput")[0].files[0]
this work for me :)
HTML
<div class="row form-group my-2">
<div class="col-12">
<div class="">
<div class="text-center">
<label for="inpImage" class="m-2 pointer">
<img src="src/img/no-image.jpg" id="img-visor" height="120" class="rounded mx-auto d-block">
</label>
<input type="file" class="visually-hidden" accept="image/*" name="picture" id="inpImage">
</div>
</div>
</div>
</div>
jQuery
$('#inpImage').change(()=>{
const file = $('#inpImage').prop("files")[0];
const imagen = URL.createObjectURL(file);
console.log(URL.createObjectURL(file));
$('#img-visor').attr('src', imagen);
});
<script src="~/fileupload/fileinput.min.js"></script>
<link href="~/fileupload/fileinput.min.css" rel="stylesheet" />
Download above files named fileinput add the path i your index page.
<div class="col-sm-9 col-lg-5" style="margin: 0 0 0 8px;">
<input id="uploadFile1" name="file" type="file" class="file-loading"
`enter code here`accept=".pdf" multiple>
</div>
<script>
$("#uploadFile1").fileinput({
autoReplace: true,
maxFileCount: 5
});
</script>
<!DOCTYPE html>
<html>
<head>
<script>
function handleFileSelect()
{
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('The File APIs are not fully supported in this browser.');
return;
}
var input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
var file = input.files[0];
var fr = new FileReader();
fr.onload = receivedText;
//fr.readAsText(file);
//fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
fr.readAsDataURL(file);
}
}
function receivedText() {
document.getElementById('editor').appendChild(document.createTextNode(fr.result));
}
</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
<div id="editor"></div>
</body>
</html>

Categories

Resources