Upload Image VarBinary(max) using AngularJS and WebService (.asmx) - javascript

I am still new in AngularJS and I want to create a form that allow me to upload an image and save it to a database and view it on a html page.
.asmx File
public void AddCard(int id, string cName, string cCoName, string cTpNmbr, string cEmail, string cAddress, string cStatus,string cScan)
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
byte[] cScan = File.ReadAllBytes(imageFilePath);
SqlCommand cmd = new SqlCommand("Insert into tblCards(Id, Name, CoName, TpNmbr, Email, Address, Status, Scan) values('"+id+"','"+cName+"', '"+cCoName+"','" +cTpNmbr+"', '"+cEmail+"', '"+cAddress+"', '"+cStatus+"',#cScan)", con);
SqlParameter param = cmd.Parameters.AddWithValue("#cScan", cScan);
param.DbType = DbType.Binary;
con.Open();
cmd.ExecuteNonQuery();
}
}
.html File
<form>
<fieldset>
<legend> ADD CARD / EDIT CARD </legend>
<p> ID : <input type="text" ng-model="cards.id" /></p>
<p>Name : <input type="text" ng-model="cards.cName" /></p>
<p>Co. Name :<input type="text" ng-model="cards.cCoName" /></p>
<p>Tp. Number : <input type="text" ng-model="cards.cTpNmbr" /></p>
<p>Email : <input type="text" ng-model="cards.cEmail" /></p>
<p>Address : <textarea ng-model="cards.cAddress"></textarea></p>
<p>Status : <input type="text" ng-model="cards.cStatus" /></p>
<p>Card Scan : <input type="file" ng-model="cards.cScan" /></p>
<button type="button" class="btn btn-primary" ng-click="addCard(cards)"> Add Card </button>
<button type="button" class="btn btn-primary" ng-click="editCards(cards)"> Edit Card </button>
<button type="reset" class="btn btn-primary"> Reset Form </button>
</fieldset>
</form>
AngularJS File
$scope.addCard = function (card) {
var id = card.id
var cName = card.cName;
var cCoName = card.cCoName;
var cTpNmbr = card.cTpNmbr;
var cEmail = card.cEmail;
var cStatus = card.cStatus;
var cAddress = card.cAddress;
var cCount = card.cCount;
var cScan = card.cScan;
cCount = 0;
$http({
url: 'CardServices.asmx/AddCard',
params: {
id: id,
cName: cName,
cCoName: cCoName,
cTpNmbr: cTpNmbr,
cEmail: cEmail,
cStatus: cStatus,
cAddress: cAddress,
cScan:cScan
},
method: 'GET'
}).then(function (response) {
GetAllCards();
alert("Card Added to Database!");
});
}
I looked up online and I've tried to use the code but it seems like it is
not working.
Thanks in advance

Related

Dynamically addint input text boxs to Asp.Net core View C# + JS

Im trying to add a function to add any amount of user requested textboxes my EventMembers input.
I have the functions working but the additional textbox inputs are not being added to my EventMembers List. I know if i just create multiple textboxes on my view by doing
EventMembers[0]
EventMembers[1]
EventMembers[2]
etc.. That works fine. How would i go about accomplishing the same thing with my javascript functions for dynamic textboxes? Code below with required info only.
Model:
public class Event
{
public List<string> EventMembers { get; set; }
}
View:
<div class="form-group" id="firstdiv">
<label asp-for="EventMembers" class="control-label">Event Members</label>
<input asp-for="EventMembers" class="form-control" />
<input type="button" class="btn btn-primary" value="Add Member"
onclick="DynamicText()" />
<span asp-validation-for="EventMembers" class="text-danger"></span>
<span style="color:red;">#TempData["MustEnterinput"]</span>
</div>
Javascript:
function DynamicText() {
var division = document.createElement('DIV');
division.innerHTML = DynamicTextBox("");
document.getElementById("firstdiv").appendChild(division);
}
function DynamicTextBox(value) {
return '<div><input asp-for="EventMembers" class="form-control" /><input type="button" class="btn btn-primary" onclick="ReTextBox(this)" value="Remove" /></div>';
}
function ReTextBox(div) {
document.getElementById("firstdiv").removeChild(div.parentNode.parentNode);
}
I changed some names for my setup.
Model;
public class EventMemberList
{
public List<string> EventMembers { get; set; }
}
Controller, Get Action;
public IActionResult Index()
{
EventMemberList model = new EventMemberList
{
EventMembers = new List<string>()
};
return View(model);
}
Controller, Post Action;
[HttpPost]
public IActionResult Index(EventMemberList model)
{
//Do Something...
return View(model);
}
Finaly View ;
#using (Html.BeginForm())
{
<div class="form-group" id="firstdiv">
<label class="control-label">Event Members</label>
<div id="inputList"></div>
<br />
<a class="btn btn-primary" onclick="AddInput()">Add Member</a>
<br />
<button type="submit">Submit</button>
</div>
}
<script type="text/javascript">
function AddInput() {
var inputList = document.getElementById("inputList");
var inputCount = inputList.getElementsByTagName('input').length;
var newInput = `
<input class="form-control" id="EventMembers_${inputCount}" name="EventMembers[${inputCount}]" type="text" value="">
<br/>
`;
var element = document.createElement("div");
element.innerHTML = newInput ;
inputList.appendChild(element);
}
</script>
To append input, I created a div. You need to add id like EventMembers_${inputCount} and name like EventMembers[${inputCount}]. With doing this, you will be able to send data to controller.
If you want to some validation in model, you need to add to inputList some code ;
<div id="inputList">
#for (int i = 0; i < Model.EventMembers.Count; i++)
{
#Html.EditorFor(_ => Model.EventMembers[i], new { htmlAttributes = new { #class = "form-control" } })
<br />
}
</div>
By doing this, when you submit list and model is not valid, you will be able to send invalid inputs to view back.

Spring Boot: Pass hashmap and open new page

I am quite new to all web development, and I am struggling to find what I am looking for. I am using springboot.
My expectation:
The user will open a page, fill the form details, click on Submit button and get redirected to a new page. The form information will be stored on a hashmap and used on my backend.
Reality:
The user opens the page, fill the form details, click on the Submit button but don't get redirected to a new page. Nonetheless, the information is stored on a hashmap.
HTML:
<div class="container" ng-app="app">
<h1>Configurador de Plugin</h1>
<div ng-controller = "plugins">
<form>
<div class="form-group">
<label>Database Details:</label>
<input type="text" class="form-control" id="hostname" placeholder="Informe o Endereço do Servidor" ng-model="hostname">
<input type="text" class="form-control" id="port" placeholder="Informe a porta" ng-model="port">
<input type="text" class="form-control" id="username" placeholder="Informe o usuário" ng-model="userdb">
<input type="text" class="form-control" id="userpass" placeholder="Informe a senha" ng-model="userpass">
<input type="text" class="form-control" id="database" placeholder="Informe qual o banco de dados" ng-model="database">
<button ng-click="validar()" type="submit" class="btn btn-default">Search</button>
<div ng-show="visivel">
<p>{{valor}}</p>
</div>
</form>
<div>Make a choice</h3>
</div>
<div class="radio">
<label><input ng-model="plugin.Name" value="test" type="radio" name="Test">Test</label></div>
<div class="radio">
<label><input ng-model="plugin.Name" value="v2" type="radio" name="V2">V2</label></div>
<div class="radio">
<label><input ng-model="plugin.Name" value="v1" type="radio" name="V1" >V1</label></div>
Texto:
<p>{{plugin.Name}}</p>
<br>
<button ng-click="sendForm()" type="submit" class="btn btn-default">Search</button>
</div>
</div>
The JS:
app.controller('plugins', function($scope, $http, $location) {
$scope.validar = function(){
$scope.visivel = true;
$scope.valor = $scope.hostname,
console.log($scope.hostname)
}
$scope.enviarForm = function(){
var url = $location.url() + "test";
var config =
{
headers :
{
'Content-Type': 'application/json;charset=utf-8;'
}
}
console.log($scope.hostname);
var data =
{
hostname: $scope.hostname,
port: $scope.port,
username: $scope.username,
userpass: $scope.userpass,
database: $scope.database
};
$http.post(url, data, config).then(function (response)
{
$scope.postResultMessage = "Sucess!";
},
function (response) {
$scope.postResultMessage = "Fail!";
});
}
});
The Controller:
#RequestMapping("/test")
public ModelAndView CadastroEnotas(#RequestBody HashMap<String, Object> data) {
ModelAndView modelAndView = new ModelAndView("newPage");
modelAndView.addAllObjects(data);
return modelAndView;
}
So, my expectation, is that the above Controller would send the user to newPage, but it doesn't.
I am googling but I am likely misunderstanding the concept of ModelAndView or maybe how to execute the function on my js...
I think the closest to what I am looking for is described here: angular event success when submit form it opens popup, but I failed to make it work. Could someone point me what I am doing wrong?
Propably use redirect.
ModelAndView modelAndView = new ModelAndView("redirect:/newPage.htm");
modelAndView.addAllObjects(data);
return modelAndView;
Or try redirect after post request: $location.path('/newPage').
Check something like this: Redirects

HTML calling Java Methods

The outcome of the scripts below is to have the HTML call the Java file, and have that Java file execute with the text that was extracted from the HTML text-boxes. I've made sure the API's (servlet, APEX) are correctly installed.
Java
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
#SuppressWarnings("serial")
public class webConnAPI extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User temp = new User();
temp.setfname(request.getParameter("fname"));
temp.setlname(request.getParameter("lname"));
temp.setEmail(request.getParameter("email"));
temp.setPword(request.getParameter("pword"));
EmailServer addUser = new EmailServer();
addUser.Users.add(temp);
}
JavaScript Function Called by the button
<script>
function addData(){
try{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var data = xhr.responseText;
alert(data);
}
}
xhr.open('GET', 'webConnAPI', true);
xhr.send(null);
}catch(Excetpion){
alert('didnt work');
}
}
</script>
HTML
The Text boxes and the buttons.
<form name="form" action="${pageContext.request.contextPath}/webConnAPI" method="post">
<fieldset>
<legend>
<h2>
<!--Not Useful to Question-->
</h2>
</legend>
<div class="separator"></div>
<p>
<!-- not Important to Question-->
</p>
<p>
<label>Email</label>
<input type = "text"
id = "email"
value = "Email"
name = "email"/>
</p>
<p>
<label>Password</label>
<input type = "password"
id = "pword"
value = "password"
name = "pword"/>
</p>
<p>
<label>First Name</label>
<input type = "text"
id = "fname"
value = "First Name"
name = "fname"/>
</p>
<p>
<label>Last Name</label>
<input type = "text"
id = "lname"
value = "Last Name"
name = "lname"/>
</p>
<div>
<button type="submit" id="buttonJoin" onclick="addDate()">Join</button>
</div>
<div>
<button onclick="buttonLogin" type="submit" name="buttonLogin">Login</button>
</div>
<div>
<button onclick="buttonReset" type="reset" nwame="buttonReset">Reset</button>
</div>
</fieldset>
<div id="data"></div>
<div id="showDiv" style="display:none;">Thanks</div>
</form>
I really don't understand the problem and I would be very grateful if I could get some help. Thanks in advance.
<button type="submit" id="buttonJoin" onclick="addDate()">Join</button>
you misspelled addData() method in onClick event of Join Button.

Read the file name using tag <input type = "file" > while uploading and rename it mvc + angularjs

I want to read the file name while uploading and rename it,save it to a path. For uploading the file I am using an upload image placed in a table. I am using -
#using (Html.BeginForm("file", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
to read the file name and the row values. But the issue is it reads the value of only first row whereever I click. Here is my code -
HTML -
<div>
#using (Html.BeginForm("file", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr ng-repeat = "{{data in list}}">
<td>{{data.Name}}</td>
<td>{{data.Id}}</td>
<td>
<label for="file">
<i class="fa fa-upload" id="hello" aria-hidden="true" >
</i>
</label>
<input type="file" name="file" id="file" onchange="this.form.submit();" />
<input type="text" name="Name" id="Name" />
<input type="text" name="Id" id="Id" />
</td>
</tr>
</table>
}
</div>
Controller -
public ActionResult file(HttpPostedFileBase file, string Name, string Id)
{
if (file != null && file.ContentLength > 0)
{
string fileName = file.FileName;
string newName = Name;
string fileId = Id;
}
else
{
ViewBag.Message = "You have not specified a file.";
}
return View("UploadPage");
}
Atpresent this is working but when I click on any upload image button, it only takes the first row Name and Id. I am not able to fix it. Please help.
Thanks
you are getting first row because when this.form.submit(); event triggers it will submit the form with all the rows in it and in action its just HttpPostedFileBase not List<HttpPostedFileBase> so it will get the data of first row because it will match the parameter. so one solution is you do
public ActionResult file(List<HttpPostedFileBase> file, List<string> Name, List<string> Id)
{
for (int i = 0; i < file.Count; i++)
{
var name = Name[i];
}
}
and a better way is to use a class
public class UploadFiles
{
public HttpPostedFileBase File { get; set; }
public string Name { get; set; }
public int Id { get; set; }
}
and your view will be
<div>
#using (Html.BeginForm("file", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr ng-repeat = "{{data in list}}">
<td>{{data.Name}}</td>
<td>{{data.Id}}</td>
<td>
<label for="file">
<i class="fa fa-upload" id="hello" aria-hidden="true" >
</i>
</label>
<input type="file" name="files[{{$index}}].File" id="file" />
<input type="text" name="files[{{$index}}].Name" id="Name" />
<input type="text" name="files[{{$index}}].Id" id="Id" />
</td>
</tr>
</table>
<button type="submit" >Upload All</button>
}
</div>
and in your action
public ActionResult AddAuto(List<UploadFiles> files)
{
foreach (var file in files)
{
// here you can access properties e.g file.File
}
}

Post dynamic form field data to spring rest controller using ajax

I am trying to submit dynamic form data to spring controller using ajax so that i could save list of object later to the database. Everything is set but i am not able to handle dynamic form data in the ajax part. The problem is how to create the javascript object for each row of table and post those objects as JSON data.
All the code is like this:
HTML
<html>
<head>
<title>Add Students</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="form-group">
<form id="student_detail" name="student_detail">
<table class="table table-bordered" id="student_dynamic_table">
<tr>
<td><input type="text" name="name[]" id="name" placeholder="Enter Name" class="form-control name_list" /></td>
<td><input type="text" name="age[]" id="age" placeholder="Enter Age" class="form-control age_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">+</button></td>
<tr>
</table>
<input type="button" class="btn btn-info" id="submit" name="submit" value="Submit" />
</form>
</div>
</div>
</body> </html>
JS
$(document).ready(function(){
var i=0;
$('#add').click(function(){
i++;
$('#student_dynamic_table').append('<tr id="row'+i+'"> <td><input type="text" name="name[]" id="name'+i+'" placeholder="Enter Name" class="form-control name_list" /></td><td><input type="text" name="age[]" id="age'+i+'" placeholder="Enter Age" class="form-control age_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">x</button></td><tr>');
});
$(document).on('click','.btn_remove', function(){
var button_id=$(this).attr("id");
//id of the clicked button
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
var url= "${pageContext.request.contextPath}";
var student = ({
name : $('#name').val(),
age : $('#age').val()
});
$.ajax({
type : "POST",
url : url + '/submitDynamicForm',
data:JSON.stringify( student),
dataType : 'json',
contentType : 'application/json',
success : function(response)
{
}
}); }); });
Controller
#Autowired
private StudentDao studentDao;
#RequestMapping(value = "/dynamic", method = RequestMethod.GET)
public ModelAndView geDynamicForm() {
ModelAndView form = new ModelAndView("dynamicform");
return form;
}
#RequestMapping(value = "/submitDynamicForm", method = RequestMethod.POST)
public void saveUser(#RequestBody List<Student> student) {
studentDao.insertListOfStudent(student);
} }
Model
#Entity
public class Student {
#Id
#GeneratedValue
private Long id;
#Column(name = "name")
private String name;
#Column(name = "age")
private int age;
// getters setters
}
Hibernate to insert list of students
#Transactional
public void insertListOfStudent(List<Student> student) {
Session session = sessionFactory.getCurrentSession();
for(Student std : student) {
session.save(std);
}
Thank You in advance
var totalRow=$('#student_dynamic_table tr').length; // last row count
var data={}; //object
for (i = 0; i < totalRow; i++) {
data[$("#row"+i).val()] = $("#age"+i).val(); // adding value to data object which will be in key value format({"ram:"21","hari":"25"})
}
data: { "jsonData": JSON.stringify(data) }, // on your ajax data submit
so now in you controller you can get the data with .key() and .value() but make sure you parse with JSON.parse before .

Categories