Better Way to Change Image src While being async [angular 4]? - javascript

I have a problem which was solved by a hack and I'm looking for a better way to solve it.
What I want to do is when the user clicks input:file and selects an image it should be displayed on screen without upload (using FileReader).
The problem is, I can't reach almost anything inside Filereaders onload method (I need to reach this.image for changing image) sadly I used
let el = <HTMLImageElement>document.querySelector(".veik");
el.src = this.result;`
My code
html:
<input type="file" name="test" id="file" (change)="onChange($event)">
ts:
onChange($event){
this.readThis($event);
}
ReadThis(inputValue: any) : void {
var file:File = inputValue.target.files[0];
var myReader:FileReader = new FileReader();
myReader.onload = function(e){
let el = <HTMLImageElement>document.querySelector(".veik");
el.src = this.result;
};
myReader.readAsDataURL(file);
}

Maybe you can try to use a FileItem type to get access to the temporary file
For example:
[1]. Change your (inputValue: any) to a generic FileItem class, like:
(inputValue: FileItem),
[2] Create a constant to get access to the uploaded file, like :
const file: File = item._file
Now you can access things like file.name , file.size etc.
Hope that helps.
Cheers

Related

Can't add omouseover attribute dynamically from javascript

I'm trying to add the attributes dynamically to an img tag but only onmouseenter is not been included else everything is been added perfectly
let img_elem = document.createElement('img')
img_elem.src = movies[i].large_cover_image
img_elem.alt = 'poster'
img_elem.id = i
img_elem.className ='poster'
img_elem.onmouseover = 'give_me_id(this)'
This is my HTML after adding attributes dynamically
<img src="https://yts.mx/assets/images/movies/woodstock_99_peace_love_and_rage_2021/large-cover.jpg" alt="poster" id="0" class="poster">
Just an issue with onmouseover else everything working perfectly.
I have already found other ways to add onmouseover attribute but the above method seems to be easier than I have used, so let me know the issue here. Thank you in advance
It's not working because we are trying to add the attribute but what we really want is add event listener. Below is the code please try it out
let img_elem = document.createElement('img');
img_elem.src = 'https://upload.wikimedia.org/wikipedia/commons/1/12/User_icon_2.svg'
img_elem.alt = 'poster';
img_elem.id = 'img1'; //i;
img_elem.className ='poster';
img_elem.addEventListener("mouseover",function(event){console.log('mouseover');});
document.getElementById('imgParent').appendChild(img_elem);
<div id='imgParent'>
</div>
I'm guessing that you're following the W3Schools example, but the example is adding a method through the attribute. You can't really do that in javascript code. Instead, you send in a function and then use event.target to get which image that the user is hovering. I'm taking one more step, and using shorthand properties (I think that's the name) to get target directly by using {target}.
Another way is to add an eventlistener instead, like in Bharat's answer.
const imageIds = [100, 200, 400];
for (const id of imageIds) {
let img_elem = document.createElement('img');
img_elem.src = `https://picsum.photos/id/${id}/200/200`;
img_elem.alt = 'poster';
img_elem.id = id;
img_elem.className = 'poster';
img_elem.onmouseover = giveMeId;
document.body.appendChild(img_elem);
}
function giveMeId({target}) {
console.log('id:', target.id);
}

Upload image with a single button in html

I'm a newbie in html/javascript and made two buttons that can upload image (choose file button and upload button).
However, I want to make it to just a single button and don't know how to combine those two button. I already searched on google, they said we can use onchange to combine submit button but I already have onchange function that can show image right away after choosing image file to iframe.
Here is my html code for <form>
<form action="/upload", method="post", enctype="multipart/form-data">
<div style='height:0px; width:0px; overflow:hidden;'><input type="file" name="upFile" id="upFile" onchange="getCmaFileView(this, 'name').submit()" target="dropzone_1"/></div>
</form>
Also, here is my script and button
<script type = "text/javascript">
function getFile(){
document.getElementById("upFile").click();
}
</script>
...
<li><a onclick="getFile()" style="cursor:pointer; color:#000000;">Choose File</a></li>
I tried with adding .submit() in onchange, but it didn't work.
Does anybody have an idea for this?
Please please help me out here!
Thanks in advance.
EDIT
function getCmaFileInfo(obj,stype) {
var fileObj, pathHeader , pathMiddle, pathEnd, allFilename, fileName, extName;
var file;
var img, reader;
// file = upload.files[0];
upload = document.getElementsByTagName('input')[0];
holder = document.getElementById('dropzone');
reader = new FileReader();
file = upload.files[0];
var iupload, holder;
reader.onload = function (event) {
img = new Image();
//console.log(event.target.result);
img.src = event.target.result;
img.width = document.getElementById("dropzone").clientWidth;
img.height= window.innerHeight;
// note: no onload required since we've got the dataurl...I think! :)
holder.innerHTML = '';
holder.appendChild(img);
};
reader.readAsDataURL(file);
}
function getCmaFileView(obj,stype) {
getCmaFileInfo(obj,stype);
}
Can't you just add one more function/code in your getCmaFileView() - Which will just submit the form? Also it will be called after your image viewing part is done so that may solve your problem.
function getCmaFileView(obj,stype) {
getCmaFileInfo(obj,stype);
//form.submit() OR call_to_your_submit_function();
}

How to choose a file with Javascript?

I am trying to create a Browser Dialog to let the user upload images to my webpage.
I know that I have to use an <input type="file"> but I do not know where (or better, when) retrieve the information when the user has accepted the prompt that appears when you click on the button.
In my case, when you click on a button, the prompt appears and I handle this event via Javascript.
Here is my code:
window.onload = function(){
var buttonFile = document.getElementById("buttonFile");
var file = document.getElementById("file");
buttonFile.onclick = function(){
document.getElementById("file").click();
}
var files = document.getElementById('file').files[0]; //I do not know where to put this line
alert(files);
};
#file{
display: none;
}
<input type="file" id="file" accept=".jpg, .png, .jpeg">
<button id="buttonFile">Upload file</button>
Of course, now is retrieving undefined because I am trying to retrieve it regardless if the prompt has appeared or not. If I put the line inside the onclick event of the button it also does not have the info yet. I also tried to create an onclick event for the file, but it also does not retrieve the info because it does not know when it has been accepted.
So here I have some questions:
Where should I put this line to get the value of the image that I am uploading?
As the filter of the input is not supported for old browsers, should I check it on the server side also, right?
If I want to check it on the server side (PHP), have I to link it to a form?
Thanks in advance!
You've got everything right so far, except you don't need to get the value of the files until the user has uploaded them. Otherwise, it will definitely be undefined.
window.onload = function() {
var buttonFile = document.getElementById("buttonFile");
var file = document.getElementById("file");
buttonFile.onclick = function() {
document.getElementById("file").click();
};
file.onchange = function(e){
if (this.files && this.files[0]) {
alert(JSON.stringify(this.files[0]));
}
};
};
1) You shouldn't put the line in the onclick handler at all.
2) You're correct in that older browsers don't check for the type. Regardless you should ALWAYS do server side validation.
3) Unless you decide to use web services.
window.onload = function() {
var buttonFile = document.getElementById("buttonFile");
var file = document.getElementById("file");
buttonFile.onclick = function() {
document.getElementById("file").click();
};
file.onchange = function() {
alert(file.files[0].name);
};
};
#file{
display: none;
}
<input type="file" id="file" accept=".jpg, .png, .jpeg">
<button id="buttonFile">Upload file</button>

Javascript image upload and display

My basic task is select image and display it,without saving it in database.
For this
1.I have made a select tag in html,through which I can upload the image.
2.I have made a blank image tag in which at there is no image source,alternate is upload image.
3.select tag has onchange javascript event handler which calls javascript function changeimage.
<script>
function changeimage()
{
document.form_name.imagetag.src=document.form_name.filetag.value;
}
</script>
In above Code
form_name : Is the name of my form
<form name = "form_name">
imagetag : Is the name of my Img tag
<Img src=" " name = "imagetag">
filetag : Is the name of my
<input type="file" name = "filetag" onchange="changeimage()">
I have save file using php extension.And when I try to print the value of filetag it shows "C:\fakepath\image.png",display this address for all image.
I have save my php file in www location.
I am using window 7,wamp server and chrome latest version.
You may want to checkout this solution (where my code derives from). It involves a little bit of jQuery but if you truly must write it out in pure JS, here you go.
Note: I modified your tags to conform to the JS below. Also try to stay away from writing any inline scripts. Always good to keep your HTML and JS loosely coupled.
var fileTag = document.getElementById("filetag"),
preview = document.getElementById("preview");
fileTag.addEventListener("change", function() {
changeImage(this);
});
function changeImage(input) {
var reader;
if (input.files && input.files[0]) {
reader = new FileReader();
reader.onload = function(e) {
preview.setAttribute('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
<input type="file" id="filetag">
<img src="" id="preview">
You can also use the Image() constructor. It creates a new HTML Image Element.
Example -
document.getElementById("filetag").addEventListener("change", function(e) {
let newImg = new Image(width, height);
// Equivalent to above -> let newImg = document.createElement("img");
newImg.src = e.target.files[0];
newImg.src = URL.createObjectURL(e.target.files[0]);
output.appendChild(newImg);
});
Reference - https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
You need one input tag to upload file and a image tag to render on the site.
The HTML and Javascript should look like
const renderFile = () => {
const render = document.querySelector('img')
const file = document.querySelector('input[type=file]').files[0]
const reader = new FileReader();
reader.addEventListener('load' , ()=> {
render.src = reader.result;
}, false)
if(file){
reader.readAsDataURL(file);
}
}
<input type = 'file' onchange = 'renderFile()' >
<br>
<br>
<img src = "" alt='rendered image' id='rendered-image' >
Simply on every upload the web page will show the image uploaded
You can Style the height and width of the image according to the need

Display Image Using Upload JS

I want to display the image using the upload form and submit button.
But the problem though, I can't make the image appear.
Here's what I did.
function myFunction() {
var x = document.getElementById("myFile").value;
document.getElementById('myImg').src = document.getElementById("myFile").name;
<form>Select a file to upload:
<input type="file" id="myFile" name=filename>
</form>
<button type="button" onclick="myFunction()">Upload This</button>
<img id="myImg" src="">
I just don't know what seems to be the problem with this.
Thank you for helping me out.
The browser does NOT allow javascript full access to the .value property of an input tag with type="file". This is for security reasons so no local path information is made available to javascript.
Thus, you can't set a .src value on an image tag based on a file input value that the end-user specified.
If you don't want to upload the image to server side, you have a possibility to do it only in the client side.
add a div to your html (dom):
<div id='bottom'>
<div id='drag-image' class='holder-file-uploader bottom-asset'> Drag here an image</div>
</div>
add this javascript:
<script>
var holder = document.getElementById('drag-image');
holder.ondragover = function () { return false; };
holder.ondragend = function () { return false; };
holder.ondrop = function (event) {
event.preventDefault && event.preventDefault();
//do something with:
var files = event.dataTransfer.files;
console.log(files);
bottomFileAdd(files, 0);
return false;
};
//Recursive function to add files in the bottom div
//this code was adapted from another code, i didn't test it
var bottomFileAdd = function (files, i) {
if(!i) i=0;
if (!files || files.length>=i) return;
var file = files.item(i);
var img = document.createElement('img');
var bottom = document.getElementById('bottom'); //this string should not be static
bottom.appendChild(img);
var reader = new FileReader();
reader.onload = function (event) {
console.log(event.target);
img.src = event.target.result;
bottomFileAdd(files, i+1);
};
reader.readAsDataURL(file);
}
</script>
note: It may not work in older browsers.
I hope it helps.
You tried to set the src attribute of the <img> tag to a local file path. However, the web browser doesn't expose the local file URL (file://...) in the value property of the <input> tag. The browser implementation may vary; Chrome, for example, gives you a fake path.
You can load the image by the FileReader API into a data URI and show it by setting the src attribute of the <img> tag:
function myFunction() {
var myFile = document.getElementById("myFile");
if (myFile.files && myFile.files.length) {
if (typeof FileReader !== "undefined") {
var fileReader = new FileReader();
fileReader.onload = function(event) {
document.getElementById("myImg").src = event.target.result;
};
fileReader.readAsDataURL(myFile.files[0]);
} else {
alert("Your browser doesn't support the FileReader API.")
}
} else {
alert("No file was selected.")
}
}
You need a fairly modern web browser for this to work:
Browser Firefox Chrome IE Opera Safari
Version 3.6 7 10 12.02 6.0.2
You can have a look at a working sample page. The final implementation of such image preview should set the <img> element to a fixed size, but your markup with my function is enough as a simple demonstration.

Categories

Resources