I'm using ngFileUpload to upload images to a server upon form submit.
I can upload an image and it appears on the screen without a problem. However, as soon as I hit submit, I get a pattern error. When I subsequently remove the image from the input, I can submit the form, and the image actually gets submitted, since it hasn't been deleted in the controller.
Here is my HTML:
<div class="col-xs-12 col-sm-4 img-responsive">
<h4>Product Featured Image:</h4>
<div ngf-drop ngf-select ng-model="vm.product.featured_image" class="drop-box"
name="featured_image" ngf-drag-over-class="'dragover'"
accept="image/*" ngf-pattern="'image/*'" ngf-max-size="2MB"
ngf-change="vm.upload($files, $invalidFiles)">
<span>Drop</span>
<div class="col-xs-12" ng-show="vm.product.featured_image">
<img ngf-src="vm.product.featured_image" class="img-responsive">
</div>
</div>
<div class="text-center text-red" ng-show="editForm.featured_image.$error.maxSize">
Max file size is 2MB. File size: {{errorFile.size / 1000000|number:1}}MB
</div>
And my controller method:
upload($files, $invalidFiles) {
if ($files.length > 0) {
let fileR = new FileReader();
fileR.onloadend = ((e) => {
this.product.featured_image = e.target.result;
});
fileR.readAsDataURL($files[0]);
}
}
Related
How do I retrieve information stored in a js file? I assume I am labelling my node elements in HTML incorrectly
I'm hoping to gain a better understanding of how to retrieve a function node from localStorage
Below are the key factors I am trying to get using getElementById into local storage from post HTML.
This is not everything in my listing.html document, I have excluded everything but what I think are essential elements
<div class="listing">
<div class="container-form">
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img class="img" value(src)="1" id="img" src="images/4.JPG" alt="img1">
</div>
<div class="infoBox">
<h5 post="weight" id="weight" value="7.00">7.00 : Under - 16 oz</h5>
</div>
<div class="column-bottom">
<div class="add-button">
<div class="add-button" method="post">
<p><input type="submit" onclick="addListing()" class="btn"></input></p>
<div class="buy-button">
<span class="price" post="price" id="price" value="60">$60</span>
<button type="button" class="btn" onclick="window.location.href='cart.html'" onclick="addListing()"
;>BuyMe</button>
</div>
</div>
</div>
</div>
</div>
</div>
I am trying to use the function below to store each element from the post HTML
function addlisting() {
let listing = ['listings'];
if (localStorage.getItem('listings')) {
listing = JSON.stringify(localStorage.getItem('listings'));
alert("added!");
}
listing.push({ 'listingId': listingId + 1, image: '<imageLink>' });
listingsId = listingsId + 1;
var listingsName = document.getElementById('name').innerHTML;
var listingsPrice = document.getElementById('price').getAttribute('data- value');
var listingsImage = document.getElementById("img").src;
var listingsWeight = document.getElementById('weight').getAttribute('data- value');
value = parseFloat(listingsPrice, listingsWeight).toFixed(2);
localStorage.getItem('name', 'price', 'img', 'weight', JSON.stringify(listingsName, listingPrice, listingsImage, listingsWeight));
}
here is the $(document).ready(function(){ function I'm hoping to implement into my code, I got this from another Stack Overflow page as it was the most fitting however I am yet to understand each component.
$(document).ready(function () {
$('#Btn').load(function () {
let listings = [];
if (localStorage.getItem('listings')) {
listings = JSON.parse(localStorage.setItem('listings'));
}
listings.push({ 'listingId': 1, image: '<imageLink>' });
});
});
my question again is how do I then execute this function using onload Onto a separate HTML, called cart.html. I did not display my cart.html file because there is nothing pertaining to this question on it. And furthermore how to go about styling Onload events that retrieve information from localStorage.
P.S.
There is an alert function within my first .js excerpt addListing(), that does not fire when clicked. probably a sign of bad programming. I've just never found a straightforward answer
I'm trying to insert modal window html code dynamically upon user click on which item otherwise i load all of the items' modal window code in the html. I also have some inputs in the modal window loading from Flask/Sql and i want to let user update any of them so i need to send data back to python on submit button clicked. But right now because of i have too many modal windows (even though they have separate ids) i couldn't find a way to achieve this
Here is my code:
routes.py
#app.route('/viewApart', methods=['GET', 'POST'])
def viewApart():
apts = []
getApts = db.engine.execute("SELECT * FROM apartments")
for a in getApts:
apts.append((a))
rooms = []
getRooms = db.engine.execute("SELECT * FROM rooms")
for r in getRooms:
rooms.append((r))
return render_template('apartments.html', title=_('Apartments'), apts=apts, rooms=rooms)
apartments.html
....
<section class="container">
<div class="row">
.. below some gallery code to show individual items from apts ..
{% for apt in apts %}
<div class="col-md-3">
<a href="javascript:void(0);" class="widget__v2 apt-widget rounded-corners box-shadow__v1 white" data-anchor="modalwindow" data-target="edit-apartment{{ apt[0] }}" id="apt{{ apt[0] }}">
<div class="widget-header">
<figure class="image h-180">
<img src="{{url_for('static', filename='_assets/img/apt/{{ apt[0] }}.jpg')}}" alt="" class="image__scaledown">
</figure>
.. below model window ..
<div id="edit-apartment{{ apt[0] }}" class="modal large">
<div class="modal-wrapper">
<div class="modal-inner">
<div class="modal-header">
<h3 class="title">{{ _('Edit Apartment') }}</h3>
</div>
<div class="modal-content">
<div class="row medium-gutter">
<div class="col-md-6">
<div class="row medium-gutter">
<div class="col-md-8">
<div class="form-group">
<div class="form-group-title clearfix">
<label for="apt_display_name">{{ _('Display Name') }}</label>
<div class="lh-24 text__default-grey pull-right" data-tooltip="true" data-tooltip-direction="up" data-multiline="true"
data-content="..">
<i class="icofont-question-circle"></i>
</div>
</div>
<input id="apt_display_name" type="text" class="form-control" value="{{ apt[1] }}">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="apt_number">{{ _('Apt. Number') }}</label>
<input id="apt_number" type="text" class="form-control" value="{{ apt[2] }}">
</div>
</div>
</div>
.. and so on...
.. and submit button ..
{{ _('Save Changes') }}
</div>
</section>
Right now even with multiple model windows, i can display the current data in modal window, so what i want to achieve this upon clicking on btnSubmit button i need to send all input values back to python so i can update my sql or insert new one. Please let me know if more code is needed..
Thanks
If I am understanding your question correctly - a skeleton version of your page would be something like this
<!DOCTYPE html>
<html>
<body>
<p>INTRODUCING MY AWESOME SITE AND 2 DIVS YOU CAN CLICK</p>
<div id="apt_1_modal">
<input id="apt_1_text"></input>
<a onclick="myFunction(event)">Submit</a>
</div>
<div id="apt_2_modal">
<input id="apt_2_text"></input>
<a onclick="myFunction(event)">Submit</a>
</div>
</body>
</html>
You will need JavaScript to handle the user interaction - the script would look something like this. You can either append this script directly to your render_template output or you can append it as a file.
The script will do 2 things - first capture what your user is inputting and second, send that data over to flask
<script>
function myFunction(e) {
//FIRST WE CAPTURE THE VALUE THAT THE USER INPUTS
let userInput = {toSend: e.currentTarget.previousElementSibling.value}
//THEN WE SEND IT TO THE FLASK BACKEND USING AJAX (Fetch API)
fetch("/api/path/to/flask/route", {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userInput)
}
</script>
Now you need a function that can handle the userInput data
Backend
from flask import Flask, request #import main Flask class and request object
#app.route('/api/path/to/flask/route', methods=['POST'])
def capture_userinput():
req_data = request.get_json()
recd_data = req_data['toSend']
your_code_to_push_data_to_db(recd_data) #Depends on your ORM/DB
I hope I have given you an idea of how to go about - You will most certainly have to change the way to capture userInput, tweak the fetch call and send/capture additional data in your flask api.
I have an HTML form described as below:
<div>
<div class="modal-header">
<h3 class="modal-title">File Attachment</h3>
</div>
<div class="modal-body">
<input type="file" id="inpFile" file-model="myFile" />
</div>
<div class="modal-footer">
<div class="btn-toolbar pull-right" role="toolbar">
<div class="btn-group" role="group" >
<button type="button" class="btn btn-default" file-upload>Upload</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default" ng-click="$close()">Close</button>
</div>
</div>
</div>
</div>
I have my angular directive (as written on the Upload statemtn in my HTML
.directive('fileUpload', ['$http', function ($http)
{
return {
restrict: 'A',
link: function (scope, element, attrs)
{
// Create the formdata and get the file
var file = document.getElementById("inpFile").files[0];
var formdata = new FormData();
formdata.append('uploadedFile', file);
ajaxUrl = root + 'FileUpload/upload';
$http.post(ajaxUrl, formdata, {
headers: { "Content-Type": undefined }
})
.success(function (status)
{
if (status.Succeed)
{
alert('File Uploaded');
}
else
{
alert(status.ErrorResult);
}
});
}
};
}])
Here is the screen shot of the attachment screen in the upper right:
The issue I'm having is this:
When I click on that attachment button, the HTML form does not come up in order for me to browse, select a file and click the upload button (where the directive is).
Instead, when clicking on the attachment button, it goes directly into the directive. It does go into my MVC controller afterwards, but no files is there to validate against since the form does not come up.
Can someone please tell me what I'm doing wrong here so the form will be able to come up first to select the file, click the upload button, then have my directive submit the file to the MVC Controller...
EDIT
Code for Attchment button which occurs on several pages:
<h3 class="panel-title">Check Deposit Header Information <attachment /> </h3>
The form is the fist screen shot of the HTML form.
I'm thinking that when you click on the Attachment button, the HTML form should come up. The when you click on the Upload button, it should hit the directive.
When you click on the "Attachment" link, the HTML code is in a directory called:
AccountingModule/modal/attachment/attachment-modal.html
I am using the following bootstrap 3 html
<form action="#" role="form">
<div class="form-group">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail" style="width: 200px; height: 60px;">
<img id="logothumb" src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" alt="" /> </div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 60px;"> </div>
<div>
<span class="btn default btn-file">
<span class="fileinput-new"> Select image </span>
<span class="fileinput-exists"> Change </span>
<input type="file" name="..." id="logo"
> </span>
Remove
</div>
</div>
</div>
<div class="margin-top-10">
Upload
Cancel
</div>
</form>
I have some javascript code to upload the file and also show an existing file from database when the code is first loaded.
var fileUploadControl = $("#logo")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
The problem is, the file upload control shows 'Select Image' even when there is
a file present i.e. shown from database in the img src. It should show the 'Change' - 'Remove' options. How do i get it to do that. It does this when a file is selected for the very first time however.
Thanks
If I understand you correctly, you will have an image present when your page is loaded. However, you only want "Change" and "Remove" visible, with "Select Image" hidden. To do this, you can simply hide your span containing "Select Image" when the page loads.
$('span.fileinput-new').hide();
Now you have your active page. If the default image is removed, I assume you want to then hide "Change" and "Remove" and then display "Select Image" again. In this case, you can set an event on your file input and toggle these based on if a file is currently uploaded or not.
$('#logo').on('change', function() {
// If a file is uploaded - hide "Select Image" and show "Change - Remove"
if($(this).val().length) {
$('span.fileinput-new').hide();
$('span.fileinput-exists, a.fileinput-exists').show();
// If a file is not uploaded - show "Select Image" and hide "Change - Remove"
} else {
$('span.fileinput-new').show();
$('span.fileinput-exists, a.fileinput-exists').hide();
}
});
EDIT - I played with this a while and have put together a JSFiddle that I think will help you out.
Check it out here
In my app, i have a web page with lots of images whose source url is generated dynamically by making get request to the rails server, initially a default image is assigned to the source. After loading the page i make request to the server that return a json with new image URl, and then need to update the src of that image. Following is the code i am using in html.erb
<div class="inner">
<div class="span9 blog-head alert alert-info"><h3><%=#feeds.title%></h3></div>
<%#feeds.entries.each do|feed|%>
<div class="thumbnail feeds span6">
<div class="row title lead">
<span class="span6"><%=link_to feed.title,feed.url,target: "_blank"%></span>
</div>
<div class="row content">
<input type="hidden" class="image-feed-url" value="<%=feed.entry_id%>">
<!-- need to update src of following img tag -->
<img class="span2 desc-img thumbnail" src="/assets/default.jpg" alt="RSS">
<span class="span3"><%=feed.summary%></span>
</div>
<div class="row footer">
<%if feed.published%>
<span class="span3">Published on: <small><%=feed.published.to_date.strftime("%b, %-d, %Y")%></span></small>
<%end%>
<span class="span2 source">Source: <small><%=link_to 'Click here',#feeds.url, target: "_blank"%></span></small>
</div>
</div>
<%end%>
</div>
Need to update src in "img" tag having class "desc-img". In my JS file
$(document).ready(function(){
all_feeds = $('.inner .feeds')
for(i=0;i<all_feeds.length;i++)
{
element = all_feeds[i]
feed_url = $(element).find('.image-feed-url').val()
$.getJSON("/get_image_url?feed_url="+feed_url,function(data){
// data['link] is the actual image link returned by server
$(element).find('.desc-img').attr('src',data['link']);
});
}
});
I had also tried using div with background image instead of img tag and updating background image of div in JS but nothing works. I am new to Jquery and Ajax, any help will be appreciated.
try this :
$.getJSON("/get_image_url?feed_url="+feed_url,function(data){
$(element).find('.desc-img').removeAttr('src');
$(element).find('.desc-img').attr('src', '../' + data['link'] + '?' + Math.random());
});
Hope this helps.