Split image path gotten from database and append to src - javascript

I have multiple image paths saved into the database in the same column. The image is saved in this sample in the database:
Two images are not uploaded every time (the highlighted is the multiple image upload example separated by comma). I am using Nodejs and am getting the image data with foreach on the ejs side (data is the output of the select statement on the index.ejs side
index.js
router.get('/homes', function (req, res, next) {
db.query("SELECT * FROM stocks", function (err, rs) {
if (err) {
console.log(err);
}
else {
res.render('homes', {data:rs})
}
});
});
<% data.forEach(function(item) { %>
<input type="hidden" id="desc" value="<%= item.image %>" />
<img id="pic1" class="pic-1" src = "" alt="image" >
<% }); %>
item.image value (input string you are getting from $('#desc').val()). It is just string format of the image path as the loop occurs.
MyImage-1591506118979.png
MyImage-1591507932201.jpg
photos-1591548210637.jpg,photos-1591548210640.png
MyImage-1591494888039.png
MyImage-1591505437596.jpg
MyImage-1591084895899.jpg
MyImage-1591085173153.jpg
MyImage-1590905192772.JPG
I am saving the image on my localhost server. I am doing the split and wanting to append the src in the script tag with the code below:
<script>
var desc = $('#desc').val();
var temp = new Array();
temp = desc.split(",");
var container = document.getElementById("container");
temp.forEach(function (imagepath) {
var img = document.createElement("img");
img.className = "class";
img.src = imagepath;
// div.innerText = text;
img.classList.add("li-added");
container.append(img);
});
document.getElementById("pic1").src= "/" + text;
</script>
I use the same format for split text and it works, but am not sure what am getting wrong in the image part. I will appreciate any assistance or any other way to achieve this. Thanks.

I still don't know exactly what you intend to do. However, I tried to tidy up your code. In the HTML I got rid of the non-unique IDs by replacing them with class attributes.
In your JavaScript code I replaced the lengthy vanilla-JavaScript expressions by suitable jquery expressions and avoided some (temporary) variables altogether. The following is valid HTML and working JavaScript but might not be what you intended:
// var desc = $('#desc').val();
var data=[{image:"MyImage-1591506118979.png"},
{image:"MyImage-1591507932201.jpg"},
{image:"photos-1591548210637.jpg,photos-1591548210640.png"},
{image:"MyImage-1591494888039.png"},
{image:"MyImage-1591505437596.jpg"},
{image:"MyImage-1591084895899.jpg"},
{image:"MyImage-1591085173153.jpg"},
{image:"MyImage-1590905192772.JPG"}];
$("#container").html(data.map(item=>
`<input type="text" class="desc" value="${item.image}" /><br>`
+ item.image.split(',').map(pth=>`<img class="pic1" src ="${pth}" alt="${pth}"><br>`)).join(''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>

Related

How do i access django form's image field in js code

I am building a BlogApp and I am Build a feature of preview image before save into Database. BUT at the last moment, I am stuck on a Problem.
As i did before, I used to access image field in template like {{ form.image }} but i put js code in template for preview the selected image in Choose file.
create_blog_post.html
General method for choose image field Choose file in browser `{{ form.image }}.
{{ form.image|as_crispy_field }}
js code in create_blog_post.html
<input type="file" id="uploadImage" name="termek_file" class="file_input"
multiple/>
<div id="result" class="uploadPreview">
<script>
window.onload = function() {
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("uploadImage");
filesInput.addEventListener("change", function(event) {
var files = event.target.files;
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load", function(event) {
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/>";
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}
});
}
}
</script>
The Problem
I have no idea , how to access {{ form.image }} attribute in js code, which can show both Preview before save and upload that image.
What have i tried
1). I have seen many answers on SO but nothing works.
2). Tried many methods BUT nothing works.
Any idea would be appreciated on , How to access {{ form.image }} in js code.
Thank You in Advance.
I'm not sure what your code is about but I think you just need to access the value given by {{ form.image }}
So do the following
const theWantedThing = "{{ form.image }}"
If you didn't include the quotes javascript will through an error
Also, this uses Django HTML template, so make sure that your javascript code is included in the HTML page, if it was in a separate file then this won't work

Trying to use array.push(); with newlines but in plain text, not html <br> tags

recently I have been trying to grab HTML form input data, add a prefix, then write that back into a <div> For example:
HTML:
<h1>Please enter Details</h1><hr>
GUID (Generator):<div id="guidInput" style="display:inline;">
<!-- Changed to an onkeyup="" method. Works the same but with less code. -->
<input onkeyup="gen()" id="guidText" style="height: 16px;"></input>
</div>
ID:<div id="idInput" style="display:inline;">
<!-- Changed to an onkeyup="" method. Works the same but with less code. -->
<input type="number" type="number" onkeyup="gen()" id="idText" style="height: 16px;"></input>
</div>
<div id="command" class="command"></div>
JS:
$(document).ready(function(){
var command = ""; /*Here for future developement*/
command += ""; /*Here for future developement*/
document.getElementById('command').innerHTML = command;
});
function gen() {
var id = $('#idText').val();
var guid = $('#guidText').val();
var command = ""; /*Here for future developement*/
var tags = [];
tags.push("GUID "+guid);
tags.push("ID "+id);
command += tags.join("<br>");
command += ""; /*Here for future developement*/
document.getElementById('command').innerHTML = command;
}
This does what I want it to: https://imgur.com/a/QrwD7 But I want the user to download the output as a file. To do this I implemented FileSaver.js, and added this code to my files:
HTML (placed above the <div id="command" class="command"></div>):
<button onclick="saver()">Save</button>
JS:
function saver() {
var text = document.getElementById("command").innerHTML;
var newText = text.replace(/(<([^>]+)>)/ig,"");
var filename = ("File")
var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
saveAs(blob, filename+".txt");
}
That grabs the content of the <div> containing the output, and triggers a download of File.txt. The contents of this file look like this (from imgur.com link above.):
GUID qwertyuiop<br>ID 12345
This is where I'm having my problem. I NEED the file to look like this:
GUID qwertyuiop
ID 12345
With a line break after every part. the <br> is for displaying it on the site, but I need some way to make sure it's on a separate line in the downloaded file, and having no HTML tags in the file.
var newText = text.replace(`<br>`, `\n`).replace(/(<([^>]+)>)/ig,"");
or
function gen(delimiter) {
// ... //
command += tags.join(delimiter);
return command;
}
function saver() {
// ... //
var newText = gen(`\n`);
// ... //
}
Your code is violating SRP: Single Responsibility Principle.
You are trying to do two things at the same time.
Prefixing and formatting in HTML are two different concerns and they should be separated.
After that, the answer will become obvious.

Reading the name of a File with Javascript/jQuery

Currently I am making a program in which works as a text editor. I have a section where you can rename the title, and when you save, it takes that document.getElementById('title').innerHTML and makes it the .txt name.
For example:
If the title div had the innerHTML of "Document", the file would be called "Document.txt".
My problem is that I want it to also upload a file and take its file name.
For example:
I uploaded a file called "Document.txt", and the function makes the title "Document". (I am using a .replace('.txt','') to make it not show in the title and a += '.txt' to make the file actually a .txt when saved.
Anyone know how to make the file name of the uploaded document using an <input type='file'> a string to be used elsewhere?
Here is some code to put it in perspective:
var id = function(id){return document.getElementById(id)};
function readText(that)
{
var reader = new FileReader();
reader.onload = function(e)
{
var output = e.target.result,
name = FILENAMEFIND();
id('page').innerHTML = output;
id('title').innerHTML = name;
}
reader.readAsText(that.files[0]);
}
Ok, I figured it out myself:
var id = function(id){return document.getElementById(id)},
input = id("upfile"),
file = input.value.split("\\"),
fileName = file[file.length-1]; // Take purely the file name
id('title').innerHTML = fileName; // Outputted to title div

Displaying remote images in a firefox add-on panel

I'm trying to display remote images in a FireFox add-on panel, but the src attributes are being converted from something like this:
http://example.com/image.jpg
to something like this:
resource://addon_name/data/%22http://example.com/image.jpg%22
I can't figure out if I'm breaking a security policy or not.
In my add-on script (index.js) I'm retrieving image URLs using the sdk/request API and passing them to my content script (data/my-panel.js). My data/my-panel.js file is creating DOM elements in my panel file (data/popup.html) – including images – using the URLs passed from index.js. Here are the relevant bits of code:
index.js
var Request = require("sdk/request").Request;
var panel = require("sdk/panel").Panel({
width: 500,
height: 500,
contentURL: "./popup.html",
contentScriptFile: "./my-panel.js"
});
Request({
url: url,
onComplete: function(response) {
// Get the JSON data.
json = response.json;
// Launch the popup/panel.
panel.show();
panel.port.emit("sendJSON", json);
}
}).get();
data/my-panel.js
var title;
var desc;
var list;
var titleTextNode;
var descTextNode;
self.port.on("sendJSON", function(json) {
json.docs.forEach(function(items) {
title = JSON.stringify(items.sourceResource.title);
desc = JSON.stringify(items.sourceResource.description);
img = JSON.stringify(items.object);
console.log(img);
var node = document.createElement("li"); // Create a <li> node
var imgTag = document.createElement("img"); // Create a <img> node
imgTag.setAttribute('src', img);
imgTag.setAttribute('alt', desc);
imgTag.style.width= '25px';
titleTextNode = document.createTextNode(title);
descTextNode = document.createTextNode(desc);
node.appendChild(titleTextNode); // Append the text to <li>
node.appendChild(descTextNode); // Append the text to <li>
document.getElementById("myList").appendChild(node); // Append <li> to <ul> with id="myList"
document.getElementById("myImgs").appendChild(imgTag);
});
});
The console.log(img) line is displaying the URLs correctly, but not in popup.html...
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul id="myList"></ul>
<p id="myImgs"></p>
</body>
</html>
How can I make the images' src attributes point directly to the remote URLs?
Thanks!
I figured out what I was doing wrong. Using JSON.stringify() on the img URL was adding double quotes around it. Removing it fixed the images:
img = items.object;
I'm not so sure about SDK permissions, but as a last resort you can turn the remote url into a resource URI like this -
var res = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
res.setSubstitution("rawr", Services.io.newURI('http://www.bing.com/',null,null));
// now try navigating to resource://rawr it will load bing
Then you can load resource://rawr and it should work.

Read an input tag into a javascript string

I'm trying to read an input type="file" tag into a javascript string. I know this should be simple but I simply cannot get my code to work. The file is plain .html. Here's what I have
<h3>Select location of html file.</h3>
<form onSubmit="submitButtonPressed()">
<input type="file" id="classList" />
<input type="submit" />
</form>
<script>
var reader = new FileReader();
var htmlFile = document.getElementById("classList").files[0]; //read the file selected with the <input> tag
reader.readAsText(htmlFile);
var htmlText = reader.result; //and create a string with the contents
function submitButtonPressed() {
var lengthOfText = htmlText.length;
alert("It is " + lengthOfText + " characters long");
}
</script>
I'm just trying to create a string that contains the contents of the .html file selected by the input tag. I can't figure out why htmlText doesn't contain the contents of the .html file, could someone explain what I'm doing wrong?
this is the right answer for you :
HTML5 File API: How to see the result of readAsText()
reader.onload = function(e) {
// e.target.result should contain the text
};
reader.readAsText(file);
so i guess you will have to check on pressing the button if the file was loaded or not , maybe it is still in progress , or encountered an error

Categories

Resources