Alternative to storing an image path - javascript

I need to dynamically generate a catalogue of items on my page. Each item consists of description data that is stored in a JSON object. Each item needs to have an image associated with it. The user fills out a form for the description data and selects an image from their computer "to upload". The javascript right now is replacing a placeholder image in the page with an image the user selects from their system. I want to be able to store the path of the image or the image itself in the JSON object. Can this be done? I have read that you cannot store the absolute file path for security reasons. I cannot use a server, or jQuery, as this is "simulated" behavior for an assignment.
EDIT: I updated the code to follow the mozilla developer tutorial suggested by Varinder but it does not work. Did I implement this incorrectly?
my html code:
<div class="uploadImgContainer">
<img src="images/upload_wText.png" id="uploadImgCont" alt="Image"/>
</div>
javascript code:
var petImg; // global variable to store petImg
function uploadPetImg(imagePath){
document.getElementById('uploadImgCont').src=imagePath;
}
window.onload=function(){
document.getElementById('uploadImageBtn').addEventListener('change',function(event){
var imagePath=URL.createObjectURL(event.target.files[0]);
uploadPetImg(imagePath);
/* to store imagePath of image */
var preview = document.querySelector('uploadImageBtn');
var file = document.querySelector('input[type=file]').files[0];
var fReader = new FileReader();
fReader.addEventListener("load", function(){
preview.src = fReader.result;
}, false);
if(file){
petImg = fReader.readAsDataURL(file);
}
});
}
When I inspect the page in Chrome, the field in the JSON object doesn't show at all. There should be a last field called petImg. The output is:
{"petName":"dash","username":"bry","petType":"cat","petBreed":"russian blue","petAge":"8","petGender":"male","petLocation":"sd","records":"yes"}
Any alternatives? Thanks in advance.

Related

How can I list the files on an FTP from a (stand-alone) .html file?

I am developing a self-contained (stand-alone) HTML form.
In one part of the form, I would like to make it possible to select the name of a file that is on an FTP.
In my .html file, I am therefore trying to find a way to list the names of all the files on an FTP.
Based on what I have read so far, it seems there is no conventional way to do this as accessing an FTP should be done using server-side languages such as PHP for example, as explained here or here.
So I am trying to see if I can do this in a different way.
An idea I had is to copy the content displayed on an FTP page into a JavaScript variable, as shown here.
I am using as an example the FTP from the German Climate Data Center because it is an open access FTP that doesn’t require any login information.
In the code below, I am trying to place the content displayed on a page of that FTP into a <div> inside my .html file, and then display the <div> using console.log.
However, as shown below, I haven’t been successful so far:
function start_FTP() {
var server = "ftp-cdc.dwd.de/test/weather/radar/sites/sweep_vol_z/mem/hdf5/filter_polarimetric/";
var ftpsite = "ftp://" + server;
window.open(ftpsite);
document.getElementById("FTP_content").innerHTML = '<object type="text/html" data=ftpsite ></object>';
console.log(FTP_content);
}
<h2> List FTP content using JavaScript </h2>
<button type="button" id="FTP_button" name="FTP_button" onclick="start_FTP()">Select File Name</button>
<div id="FTP_content"> </div>
The <div> does not contain any useful information.
This is just a step towards my final goal, which is in fact to create a new window that lists the contents on the FTP page with a checkbox next to each line, such that the user can select the name of the file he needs.
Is this possible using JavaScript?
If not, are there any other “tricks” that can be used to reach this goal using JavaScript only?
EDIT
The issue I have is that I can not do anything on the server-side (unfortunately).
I need to develop a stand-alone HTML form that needs to be sent to lots of different end users, who need to be able to use this form “as is”.
These end users (clients) need to be able to select the name of a file from a list of files that can be seen on an open access FTP.
So I am trying to copy the names of the files that are visible on an open access FTP page, and add a check box in front of each file name, such that the end user can select the check box that corresponds to the name of the file (that will be used for further data-processing).
Do you Mean something like this?
It requires Jquery.
Javascript,css and then the HTML.
function handleFileSelect (e) {
var files = e.target.files;
if (files.length < 1) {
alert('select a file...');
return;
}
var file = files[0];
var reader = new FileReader();
reader.onload = onFileLoaded;
reader.readAsDataURL(file);
}
function onFileLoaded (e) {
var match = /^data:(.*);base64,(.*)$/.exec(e.target.result);
if (match == null) {
throw 'Could not parse result'; // should not happen
}
var mimeType = match[1];
var content = match[2];
alert(mimeType);
alert(content);
}
$(function () {
$('#import-pfx-button').click(function(e) {
$('#file-input').click();
});
$('#file-input').change(handleFileSelect);
});
#file-input {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="import-pfx-button">Browse...</button>
<input type="file" id="file-input" />
<output id="list"></output>

Upload images using only Javascript or nodejs for client-side modification?

So I'm making a website as a tool people can use to generate some cards. Users have the option to upload their own backside of all the cards. However I can't find out how to allow them to upload their images.
I don't want to save the uploaded image to the server, only have access to it client side.
I've looked and found many that use jQuery (don't have it, nor have I used it before). <input type="file"> Doesn't work as it won't stay inside a select. <select><option><input type="file"></option></select> (displays outside the select, can't seem to fix that)And even more that saves the img to the server. (I want it all client-side)
I'm using browserify so NodeJS modules work, but the few I've found require an <input type="file">. I'd share what I've tried, but I've only tried using the <input> method, and it failed and I don't know what else todo.
My end goal is to:
Upload image (can't figure out).
Copy image onto a pdf.
Allow user to download pdf.
Have it all client side so server doesn't need to stress itself.
https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
You might want to read the above document and modify it according to your needs
So I found this answer via a link inside a link inside the link #Mukund Goel's anwser (bunny trail). However I'm not accepting Mukund's due to the fact his answer didn't solve my problem.
So I found out what I needed by this: link I totally didn't think to use a hidden <input> tag.
So all I need todo is do this:
(I'd make this a snippet but this doesn't work in snippets due to the need of <input type="file">)
let hiddenInput = document.getElementById('hidden');
let result = document.getElementById('result');
let img = document.getElementById('result');
document.getElementById('bttn').onclick = hiddenInput.click;
document.getElementById('sel').onchange = hiddenInput.click;
hiddenInput.onchange = function() {
let file = this.files[0];
if (!file.type.startsWith('image/')) return;
const reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
<input type="file" style="display:none" accept="image/*" id="hidden">
<button id="bttn">Click Me</button>
<select id="sel">
<option>Or change me</option>
<option>Choose me</option>
</select>
<img id="result">

Issue Setting ngImgCrop to Image URL

According to the documentation, I should be able to set the image property of the ngImgCrop directive to an image URL, instead of to a data url. However, it does not seem to be working. I have a input text box (for the user to enter the image's url), and a button, which triggers the update of ngImgCrop's source image for cropping. Here is my code so far:
Here is the definition of the ngImgCrop Element
<img-crop
image="myImage"
result-image-size="300"
area-type="square"
area-min-size="40"
result-image="product.ImageString"></img-crop>
Here is the AngularJS in the app.js
var handleUrlSelect = function getImageDataURL(evt) {
var url = (document.querySelector('#inputImageUrl')).value;
$scope.myImage = url;
};
angular.element(document.querySelector('#selectUrl')).on('click', handleUrlSelect);
The current behavior is that the source image is not being set at all. Any help would be appreciated! Thanks!

How to change an image on a site using XML data & jQuery

I have a site that has a banner at the top of the page. I've started to overhaul my HTML structure and am now getting various pieces of information that populate the site out of an XML file. My HTML that uses the jQuery is:
<script>
function myExampleSite()
{
var myURL = window.location.href;
var dashIndex = myURL.lastIndexOf("-");
var dotIndex = myURL.lastIndexOf(".");
var result = myURL.substring(dashIndex + 1, dotIndex);
return result;
}
var exampleSite = myExampleSite();
</script>
<script>
var root = null;
$(document).ready(function ()
{
$.get("Status_Pages.xml",
function (xml)
{
root = $(xml).find("site[name='" + exampleSite + "']");
result = $(root).find("headerImage");
$("td#headerImage").html($(result).text());
var imageSrc=$(root).find("headerImage").text();
$(".PageHeader img").attr("src",imageSrc);
result = $(root).find("version");
$("td#version").html($(result).text());
result = $(root).find("status");
$("td#status").html($(result).text());
result = $(root).find("networkNotes");
$("td#networkNotes").html($(result).text());
....etc etc
});
});
</script>
My XML file looks like this.
<sites>
<site name="Template">
<headerImage>images/template-header.png</headerImage>
<productVersion>[Version goes here]</productVersion>
<systemStatus color="green">Normal</systemStatus>
<networkNotes>System status is normal</networkNotes>
</site>
</sites>
I have several <site>s that all have their own data that will populate different areas of individual sites. I've ran into some snags though.
The first snag is how it currently obtains its header image:
html
<div class="container">
<div class "PageHeader"> <!-- Header image read from XML file -->
<img border="0" src=""/>
</div>
Right now it's hard-coded to be the template header image, but I need to make that generic and read the XML value for that site. So instead of being hard-coded as images/template-header.png it would read the XML value for the current site, which is still going to be the template header - but it won't for every page.
How can I read in the image string to populate my HTML so that each site has a different image depending on what's in the XML?
Edit: Edited code to match current issue. Currently, I just get a broken image, but I can still change it back to the hard-coded image URL (images/template-header.png) and it works.
As you already have the code that can extract the image URL information from the XML, which is
result = $(root).find("headerImage");
$("td#headerImage").html($(result).text());
It's now a matter of attaching that URL, to the image tag. We need to select the object, and then simply change it's src attribute. With jQuery this is actually pretty easy. It'll look something like
var root = $(xml).find("site[name='" + site + "']");
//get the image url from the xml
var imageSrc=$(root).find("headerImage").text()
//get all the images in class .PageHeader, and change the src
$(".PageHeader img").attr("src",imageSrc)
And it should work
Example
In conclusion, if you already have some values you want to put in HTML tags dynamically, it's pretty easy. There's .html("<b>bold</b>") for content, there's .attr("attrName","attrValue") for general attributes. .css("background","red") for changing CSS directly. There's also some class modifying stuff that would be useful in the future.

Change img tag using jquery from a list of items and an url stored in an item

I have a list of items displaying a link in my view like this:
#Html.ActionLink(cardPackInfo.mCard.mMasterCard.mCardName, "ViewItemDetails", "Item", null, new { #class = "cardImage", #data_id = cardPackInfo.mCard.mMasterCard.mCardImageLink})
As you can see, I'm trying to store a data in a kind of #data_id like I did.
I have a field dedicated to display an image:
<div id="image">
<img id="cardImageDiv" src="~/Images/Functional/cardback.jpg" alt="defaultCard" class="nullify"/>
</div>
and my jQuery script is like this:
$('.cardImage').mouseover(function() {
var imageSrc = $(this).attr("data-id");
alert(imageSrc);
$('#cardImageDiv').attr('src', imageSrc);
var newImage = $('#cardImageDiv').attr('src');
alert(newImage);
});
So what I'm trying to do is, when the user's mouse is over one of the link, I take the url when the image is located (which is stored in my model at cardPackInfo.mCard.mMasterCard.mCardImageLink and change the src of the current image located in the image src with the id cardImageDiv.
However the image is not changing. The two alerts are there to testify that the first data obtained is the url of the image (which may look like this: ~\Images\CardsImages\Return to Ravnica\(RTR) - 231 - NameOfTheCard.jpeg) and the second alert tells me of the current src. But the result I have is that the first image is removed and I have the small "broken link" icon. Can anyone help me out?
Can you try with the src like "/Images/etc" and lose the ~

Categories

Resources