I'm looking forward to save/upload picture in a local directory in Windows using IONIC 3 / Cordova. Indeed, the user has to choose a file (jpg) from a folder, and I want to copy this file in another directory.
I tried with this.file.copyFile(path, name, newPath, newName) but it doesn't work and I don't understand why. I also tried with file-transfer plugin (https://ionicframework.com/docs/native/file-transfer/), but it seems I have to get an endpoint in an API to upload the file.
Please find below the function I use to copy the file when the user clicks on a submit button:
private copyFileToLocalDirBrowser(namePath, currentName, newFileName) {
this.file.copyFile(namePath, currentName, "file:///C://Users//myName//Desktop//imgs//", newFileName).then(success => {
console.log("Picture imported!");
}, error => {
this.presentToast("Error:" + error);
});
}
In the constructor, I declared private file: File and the import is import { File } from '#ionic-native/file';.
The user clicks on an input node (type file), to choose the file he/she wants :
<input name="pictureID" id="inputFile" type="file" (change)="showThumb($event)"/>
And here the showThumb function:
var files = e.target.files;
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
//Getting URI :
if (e.target.result) {
this.imageURI = e.target.result;
// Render thumbnail.
var img = document.createElement("img");
img.setAttribute('src', this.imageURI);
img.setAttribute('title', theFile.name);
img.setAttribute('id', "thumb");
document.getElementById('thumb-for-browser').appendChild(img);
}
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
Then, when the user clicks on a "Submit" button, I want to save the picture that I displayed a thumb on a local directory "file:///C://Users//myName//Desktop//imgs//".
Thanks in advance for your help.
Kind regards,
Related
I have a electron application using jszip to create a zip file that the user is then able save. Everything works fine but my problem is my application uses the users download folder. Im guessing its making a temporary file. I've submitted my application to the mac store and they want me to use another location instead of the users downloads folder for the temporary file. Is there anyway I can specify the temporary location or maybe something else other then jszip that will do this?
Here is the code I use
savePNGButton.addEventListener('click', function(e) {
var zip = new JSZip();
if (WatermarkText == ""){
var img = zip.folder("images");
} else {
var img = zip.folder(WatermarkText);
}
$(".WatermarkPhoto").each(function(index) {
imgsrc = this.src;
var DataURL = imgsrc.replace('data:image/png;base64,','');
img.file(WatermarkText+index+".png", DataURL, {base64: true});
});
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, WatermarkText+".zip");
});
});
[edit]
Looking more into this it looks like my problem is not with JSZip but with chrome or FileSaver.js using the downloads folder as a temp folder for the file before the users chooses where to place the file. Is there anyway I can change the temp location for my electron app?
If anyone comes across this, I never figured a way around the HTML5 filesystem way of moving the temp file before the users selects the download location. Instead I am using nodejs file system with electrons showSaveDialog. I also had to change JSZip to use .generateNodeStream instead of .generateAsync. Below is my function that I got working for me.
savePNGButton.addEventListener('click', function(e) {
var zip = new JSZip();
if (WatermarkText == ""){
var img = zip.folder("images");
} else {
var img = zip.folder(WatermarkText);
}
$(".WatermarkPhoto").each(function(index) {
imgsrc = this.src;
var DataURL = imgsrc.replace('data:image/png;base64,','');
img.file(WatermarkText+index+".png", DataURL, {base64: true});
});
// zip.file("file", content);
// ... and other manipulations
dialog.showSaveDialog({title: 'Test',defaultPath: '~/'+WatermarkText+'.zip',extensions: ['zip']},(fileName) => {
if (fileName === undefined){
console.log("You didn't save the file");
return;
}
zip
.generateNodeStream({type:'nodebuffer',streamFiles:true})
.pipe(fs.createWriteStream(fileName))
.on('finish', function () {
// JSZip generates a readable stream with a "end" event,
// but is piped here in a writable stream which emits a "finish" event.
console.log("zip written.");
});
});
});
The problem I have is that I am not getting the value of the result here; the code alerts undefined. I want to preview the image selected by user. Can someone tell me what the issue is?
<input type="file" name="file_name" style='display: none;' id='cover_image_90' onchange="chnageBGDynamic(this, 'Cover_Iamge_90op', '0');"/>
function chnageBGDynamic(file_id_ch,change_bg_id,is_aled_othr){
var files = !!file_id_ch.files ? file_id_ch.files : [];
if (!files.length || !window.FileReader)
return; // no file selected, or no FileReader support
if (/^image/.test( files[0].type)){ // only image file
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(files[0]); // read the local file
reader.onloadend = function(){ // set image data as background of div
$("#"+change_bg_id).css("background-image", "url("+file_id_ch.result+")"); // here is the problem it dosent gets changed. i get a blank background and when checked by inspect element i get undefined src
$("#"+change_bg_id).css("background-size", "cover");
}}else{
if(is_aled_othr =='0'){
alert('Only Images Are Allowed to Upload '); return false;
}else{
$("#"+change_bg_id).css("background-image", "url(avator/icon/noticei.png)");
$("#"+change_bg_id).css("background-size", "85%");
$("#"+change_bg_id).css("background-repeat", "no-repeat");
}
}
}
Your code is almost correct; just need one small change:
Instead of
$("#"+change_bg_id).css("background-image", "url("+file_id_ch.result+")");
We need:
$("#"+change_bg_id).css("background-image", "url("+reader.result+")");
function chnageBGDynamic(file_id_ch,change_bg_id,is_aled_othr){
var files = !!file_id_ch.files ? file_id_ch.files : [];
if (!files.length || !window.FileReader)
return; // no file selected, or no FileReader support
if (/^image/.test( files[0].type)){ // only image file
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(files[0]); // read the local file
reader.onloadend = function(){ // set image data as background of div
$("#"+change_bg_id).css("background-image", "url("+reader.result+")"); // here is the problem it dosent gets changed. i get a blank background and when checked by inspect element i get undefined src
$("#"+change_bg_id).css("background-size", "cover");
}}else{
if(is_aled_othr =='0'){
alert('Only Images Are Allowed to Upload '); return false;
}else{
$("#"+change_bg_id).css("background-image", "url(avator/icon/noticei.png)");
$("#"+change_bg_id).css("background-size", "85%");
$("#"+change_bg_id).css("background-repeat", "no-repeat");
}
}
}
.result is a property of FileReader object and not of input of type file
<input type="file" name="file_name" id='cover_image_90' onchange="chnageBGDynamic(this, 'Cover_Iamge_90op', '0');"/>
<script>
function chnageBGDynamic(file_id_ch, change_bg_id, is_aled_othr) {
console.log(file_id_ch.files);
console.log(file_id_ch.value);
console.log(change_bg_id);
}
</script>
use .value to see the file name and .files which will contain all the info about the image file Fiddle and you can see the output in developer tool in console tab
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
I am trying to use jquery to take a picture from my comp via a form.
- So I want the entire URL out of the form in an array
It works + / - in Dreamweaver, but not in the explorer browsers not even chrome
The end goal is a calendar with picture / app for people with disabilities, but as long as I get to go through the phone gap
var foto= new Array();
var i=-1;
//foto=["toets.png"];
$('#fotouit').append("FOTO UIT");
$('#knop01').click(function(){
$('input:file[name=foto]').each(function(){
//alert($(this).val());
foto.push($(this).val());
foto.forEach( function(){
i++;
$('#fotouit').append(foto[i]);
$('#fotouit').append('<img src=" '+ foto[i] + ' " width="100" height="100" />');
});
});
})
I don't think it is possible to get the URL of the picture in you computer's local filesystem, but you can use Javascript's FileReader API to read the contents of the uploaded file (in your case, the picture). The read contents can be used in the src of the img element as you did in your example code.
This is an in depth explanation of what you're trying to accomplish: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
Example:
function handleFiles(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.createElement("img");
img.classList.add("obj");
img.file = file;
preview.appendChild(img); // Assuming that "preview" is a the div output where the content will be displayed.
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
}
}
Note:
You can use the multiple attribute on a file input to allow selecting many files with one input
You can use the file inputs change event to immediately capture the files rather than providing a second button to click
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.