Validation for file upload in angularjs - javascript

Hi I am developing web application in angularjs. I am developing file upload module. I have one form and inside form i have file upload control. On clicking on submit(submitting form) if the file is not uploaded then i want to make file control as red. i have designed css class to make file control red.
<div class="upload-button bank button1" ng-class="{'has-error':
vm.hasFileInputError(myFileID) }">
<div class="upload-button-icon" >
<span class="text">{{ 'ID' | translate }}</span>
<input type="file" file-modelsr="myFileID" />
</div>
</div>
I am writing validation rule in javascript.
$scope.vm = {};
function hasFileInputError(myFileID) {
return this.form2.$submitted && this.form2.myFileID.$invalid ||
form2.myFileID.$invalid && form2.myFileID.$dirty;
}
On clicking on submit button if file has not uploaded then i want to make file control as red. This is not happening. I am trying to figure out this issue but nothing worked out. May i get some help to fix this? Thank you.

You have pass your myFileID to function. then why you need $form validation? Because if any other fields are not valid then the form.&dirty always return false.
So better to change your method be like
vm.hasFileInputError = function (myFileID) {
return myFileID == undefined || myFileID == '' ? true : false
}
EDIT:
And you should read this discussion : AngularJS - Why use "Controller as vm"?

Related

How to prevent html form refresh on submit?

Hello after searching and trying a lot , i am not able to find the issue so that I am seeking your help to solve my issue.
Here I have a form while clicking on submit button it should call the javascript function and should not redirect or refresh the page .
Here I want to send mail using SMTPJS with attachments by filling the form and choosing the image once the form submitted it should call the sendEmail() function and mail should be send, but when i click on the submit button it's refreshing the page and it's not working accordingly.
<form onsubmit="sendEmail(); reset(); return false">
<div class="col-md-12">
<div class="form-floating">
<input type="file" class="form-control" id="fileupload" required>
<label for="phone">Upload file</label>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary w-100 py-3" type="submit" style="background-color: #0e2e50;">Upload</button>
</div>
</div>
</form>
<script>
function sendEmail() {
var file = event.srcElement.files[0];
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function () {
var dataUri = "data:" + file.type + ";base64," + btoa(reader.result);
Email.send({
Host: "smtp.elasticemail.com",
SecureToken :"************"
To: 'mail#mail.com',
From: "mail#mail.com",
Subject: "Form Enquiry",
Body : "Sending file:" + file.name,
Attachments : [
{
name : file.name,
data : dataUri
}]
}).then(
message => alert(message)
);
};
}
</script>
I think the issue is in this line 'var file = event.srcElement.files[0];' because from this line it's refreshing the page and a Question mark (?) is coming in the URL. ex.page.html?
One more thing if i am calling the sendEmail() function in the onchange event of the input type file then it's working fine, why so?
You have two problems.
Typo
The first is a typo and is highlighted by the browser telling you:
Uncaught SyntaxError: missing } after property list note: { opened at line 24, column 19
This exception is preventing the function from being created, so the onsubmit function errors when it calls it, and you never reach the return false that prevents the form submission.
Read the error messages in the console in the browser developer tools.
You are missing a comma between SecureToken :"************" and To: 'mail#mail.com'.
Forms don't have files
You said:
var file = event.srcElement.files[0];
Which gets the element that triggered the event (since it is a submit event, that is the <form>) and you try to read the files property from it.
The browser tells you this:
Uncaught TypeError: event.srcElement.files is undefined
Read the error messages in the console in the browser developer tools.
The files property can be found on <input type="file">, not on the <form>.
You need to find the correct element:
var file = event.srcElement.querySelector('[type="file"]').files[0];
Asides
To generally make life easier and avoid these sorts of issues:
Use a linter, like ESLint, and an editor that can use it as a plug in
Use a code formatter to indent code and help locate syntax errors
Don't use intrinsic event attributes (like onsubmit); do use addEventListener
Pay attention to what your debugging tools are telling you
Just change it a little bit:
<form onSubmit="sendEmail(event)">
...
</form>
function sendEmail(event) {
event.preventDefault();
...
}

Selenium Python - Upload image when element seems to be hidden

So basically I have problem uploading some photo using Selenium Python
input element seems to be hidden in the page so the .sendkeys method at still I run into some errors.
this is html code of the input element
<div data-react-class="ImageUploadForm" data-react-props="{}" data-react-cache-id="ImageUploadForm-0">
<input class="hidden" type="file" accept="image/jpeg, image/jpg, image/png, image/gif">
<button class="btn btn-lemonfrog text-lg" type="button">Upload photo</button>
</div>
base_path = Path(file).parent
filepath = (basepath / "../core/attachments/clientstackphoto.jpeg").resolve()
hiddenuploaderinput.sendkeys(filepath)
right now after running above code I'm getting type error :
value = (PosixPath('........./core/attachments/clientstackphoto.jpeg'),)
def keys_to_typing(value):
"""Processes the values that will be typed in the element."""
typing = []
for val in value:
if isinstance(val, Keys):
typing.append(val)
elif isinstance(val, int):
val = str(val)
for i in range(len(val)):
typing.append(val[i])
else:
for i in range(len(val)):
E TypeError: object of type 'PosixPath' has no len()
../../venv/lib/python3.7/site-packages/selenium/webdriver/common/utils.py:150: TypeError
I expect to upload photo successfully, maybe some js injection will help ?
Based on your error message, I'm not entirely convinced the error message is caused by the hidden file input. If it were, I would expect an ElementNotVisibleException.
However, I do see that the input is hidden, so we should run some JS to reveal the input and perhaps we can rule that out as a potential issue.
Code to show image input
fileInput = driver.find_element_by_xpath("//input[#type='file']")
# display file input so we can send keys
driver.execute_script("arguments[0].style.display = 'block';", fileInput)
Alternatively, you may need to execute script on the class attribute instead:
driver.execute_script("arguments[0].setAttribute('class', 'visible')", fileInput)
Once you execute JS to make the file input visible, you can just send_keys to it like any other input:
fileInput.send_keys("PATH/TO/FILE/HERE")

Dynamically add components depending on data being recieved Angular 5

I do have this working.. but I want to know if there is a better way.. because I can see how the way could potentially be a problem in the future..
Basically I have a page that brings in data and populates on the page, every time you click a 'next' button the data changes and so the page changes..
Now I have a few tools that I have set up in components and sometimes when the data says tool === true I show the tool component on the page so how Ive done it at the moment is like so
<div class="program-item">
<div class="main">
<div *ngFor="let asset of item?.fields?.asset" class="program-item_inner">
<div [innerHTML]="asset.fields.textBlock"></div>
<!-- tool -->
<app-tool *ngIf="asset.fields.tools === 'tool'"></app-bmi-tool>
<button *ngIf="asset.fields.tools == 'BMI Tracker'" class="full-width-btn program-item_next-button" (click)="next(item?.sys.id); child.getBmi();">CALCULATE BMI</button>
<button *ngIf="item?.fields?.assetType !== 'tool'" class="full-width-btn program-item_next-button" (click)="next(item?.sys.id)">{{(item?.fields?.nextButtonText == null || item?.fields?.nextButtonText == undefined) ? 'NEXT' : item?.fields?.nextButtonText}}</button>
</div>
so basically when the data has been recieved check to see if asset.fields.tools === tool and then show the tool component.. this isnt a great way to do it because I have a few tools and I would have to do that for every single one
Is there another way I could do this?

Clear form after submit image in Meteor

I’m using CFS for files upload in my Meteor App, almost everything works fine, except because when I try to upload another image, I see my previous sended image in the form, so I need to clear that form after submit the image. I've tried with .reset but it doesn't work. This is my code right now. Thanks for the help.
NewImage.html
<template name="newImage">
<div align="center">
<form align="center">
<div>
<div>
<span class="btn btn-success btn-file">
<input type="file" accept=".gif,.jpg,.png" class="myFileInputimagepub" id="image"/>
</span>
</div>
<div>
<img src="{{currentUser.profile.image}}" alt="Image" width="60px" height="60px" class="img-circle avatar-upload" value=''/>
</div>
</div>
</form>
</div>
</template>
NewImage.js
import './newImage.html';
Template.NewImage.events({
'change .myFileInputimagepub':function(evt,tmpl){
FS.Utility.eachFile(event,function(file){
fileImagespub.insert(file,function(err,fileObj){
if(!err){
var userId = Meteor.userId();
var imageurl = {
'profile.image':'/cfs/files/fileimages/' + fileObj._id
};
setTimeout(function(){
Meteor.users.update(userId,{$set:imageurl});
},2000);
}
})
})
},
'submit form':function(event,template){
event.preventDefault();
template.find("form").reset();
}
});
If the image in question is the one with class .img-circle, the issue is that its src attribute is being dynamically provided. Currently it is currentUser.profile.image. This won't clear just by resetting the form and manually clearing the image's src value would be fighting the framework.
Option 1 (Not Ideal):
If you don't want to keep the image, unset the database change made after the file upload by running something like this:
Meteor.users.update(userId, { $set: { 'profile.image': null }});
This is not ideal as it enables you to continue modifying the database with an image which may not be needed long-term.
Additionally, I'm assuming you're currently using the autopublish/insecure packages. You'll want to remove these before going public with your app as they allow any user to change the database without restriction.
Option 2:
You could save the returned value from your 'change .myFileInputimagepub' event as a ReactiveVar, then only actually run Meteor.users.update (preferably on the server using a Method) when your user submits the form. At that point you could clear the reactive variable.
Using a ReactiveVar will allow you to provide the saved URL to the src attribute via a helper, and then change the ReactiveVar's value when you wish to clear the form.
There's a simple example of manipulating ReactiveVars here: https://gist.github.com/ahoereth/a75d2d6528b1844ad503

html form - upload file to storage without php

All the exmaple I saw was with a form that redirect to file upload.php. I want to do a little differnt.
I have a form and there I have :
<input type="file" name="img1" id="img1">
and in the end of the form:
<button type="button" class="submit-button" onclick="signUp()"/> signup </button>
I want in the signUp() function to store the file in my storage and get url to thiss file.
What I did so far is :
var fileUploadControl = $("#img1")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
......................
}
but I don't know how to continue. thanks!
It is not possible to store data/file without using a server side language(like PHP,C#,...).
Else anyone could save files to your server and that is something you don't want!
I recommenced to use a combination of HTML and PHP! You will find a good documentation on http://www.php.net/manual/en/features.file-upload.post-method.php

Categories