How to send nested json objects to the controller by using ajax - json

What I am trying to do is passing nested json objects to the controller
from where I have to set the field of those entity respectively. I have two entity named UserData and Address and I want to get nested objects for both the entity as the project requires.
As you can see at this phase I don't understand how to tackle this problem. help me out of this problem.
/front end/
<body>
<div class="container">
<div class="jumbotron">
<h1>File upload Demo</h1>
<p>File upload Demo along with the JSON data</p>
</div>
</div>
<div class="container">
<div class="alert alert-success">File uploaded successfully</div>
<div class="alert alert-danger">File is not uploaded. Error occurred</div>
<div class="form-group">
<label for="firstname">First Name:</label> <input type="text"
class="form-control" id="firstname" name="firstname">
</div>
<div class="form-group">
<label for="lastname">Last Name:</label> <input type="text"
class="form-control" id="lastname" name="lastname">
</div>
<div class="form-group">
<label for="state">State:</label> <input type="text"
class="form-control" id="state" name="state">
</div>
<div class="form-group">
<label for="city">City:</label> <input type="text"
class="form-control" id="city" name="city">
</div>
<form id="fileUploadForm">
<div class="form-group">
<input type="file" class="form-control-file border" name="file">
</div>
</form>
<button type="button" id="btnSubmit" class="btn btn-primary">Submit</button>
</div>
<script>
$(document).ready(function () {
$(".alert-success").hide();
$(".alert-danger").hide();
$("#btnSubmit").click(function () {
alert("hello");
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
var jsonDataObj = {
"firstname": $("#firstname").val(),
"lastname" : $("#lastname").val(),
"address" :{
"state": $("#state").val(),
"city" : $("#city").val()
}
};
data.append("jsondata", JSON.stringify(jsonDataObj));
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/upload",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
$(".alert-success").show();
$(".alert-danger").hide();
},
error: function (e) {
$(".alert-success").hide();
$(".alert-danger").show();
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
});
});
</script>
</body>
/**controller**/
#Controller
public class FileUploadRestController {
#Autowired UserRepo userRepo;
#Autowired uploadrep upld;
ObjectMapper objectMapper = new ObjectMapper();
ObjectMapper addressmap = new ObjectMapper();
#RequestMapping(value="/upload", method=RequestMethod.POST)
public ResponseEntity<Object> uploadFile(#RequestParam(required=true, value="file") MultipartFile file, #RequestParam(required=true, value="jsondata")String jsondata) throws IOException, ParseException {
System.out.println("file name is "+file.getOriginalFilename());
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(jsondata);
//System.out.println(json.getString("firstname"));
/*File convertFile = new File("c://mydownloads//"+file.getOriginalFilename());
convertFile.createNewFile();
FileOutputStream fout = new FileOutputStream(convertFile);
fout.write(file.getBytes());
fout.close();*/
System.out.println("data ies "+json);
//UserData personData = objectMapper.readValue(jsondata, UserData.class);
//Address addressData = addressmap.readValue(jsondata, Address.class);
//Address address =new Address(addressData.getState(),addressData.getCity());
/*UserData userData=new UserData(StringUtils.cleanPath(file.getOriginalFilename()),file.getContentType(),file.getBytes(),personData.getFirstname(),personData.getLastname());
System.out.println("uploaded datafiles ");
//String str=Base64.getEncoder().encodeToString(file.getBytes());
userData.setAddress(address);
userRepo.save(userData);*/
return new ResponseEntity<>("File is uploaded successfully", HttpStatus.OK);
}

Related

Form data to accept nested schema in Javascript

I have a JSON schema which i am trying to make my form tailor, but the schema has nested objects and arrays like so:
{
"person": {
"firstName":"Kay",
"lastName":"Young"
}
"addressDetails":[
{
"line1": "line1",
"line2": "line2"
}]
}
HTML
<div class="form-group">
<label for="caseIdentifier">First Name</label>
<input type="text" class="form-control" id="firstname" name="?">
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" class="form-control" id="lastName" name="?">
</div>
<div class="form-group">
<label for="line1">Line 1</label>
<input type="text" class="form-control" id="line1" name="?">
</div>
<div class="form-group">
<label for="line2">Line 2</label>
<input type="text" class="form-control" id="line2" name="?">
</div>
JS
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function (e) {
e.preventDefault();
const url = url;
const formData = new FormData(this);
let object = {};
formData.forEach(function (value, key) {
object[key] = value;
});
let json = JSON.stringify(object);
let fetchData = {
method: 'POST',
body: json,
headers: <myHeaders>
}
fetch(url, fetchData)
.then(function (response) {
console.log(fetchData)
return response.text();
}).then(function (text) {
console.log(text);
}).catch(function (error) {
console.error(error);
});
});
How do I tailor my HTML form to match these parameters in JS? please.
....................................................................................................................................................................................................................................................................................................................................................................................................................................................................

file upload angular - spring boot - mysql

I had a working post api sending formdata to the back end and posting it to the DB .
when I added an input file type to the form and appended it the dataform, I got errors.
I always have this error:
"error: "Internal Server Error"
message: "Unrecognized field "file" (class org.sid.model.User), not marked as ignorable (6 known properties: "fileName", "id", "email", "name", "password", "logo"])↵ at [Source: (String)"{"name":"ss","email":"sss","password":"ssssssss","file":"C:\fakepath\ooredoo_758118.png"}"; line: 1, column: 58] (through reference chain: org.sid.model.User["file"])"
path: "/users"
"
Controller
#CrossOrigin(origins = { "http://localhost:4200", "http://localhost:9000" }, maxAge = 36000)
/*#RequestMapping(value="/users" , method=RequestMethod.POST)*/
#RequestMapping(value="/users" , headers = ("content-type=multipart/*"), method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE ,
produces = { "application/json" }
)
public User save(#RequestPart("file") MultipartFile f ,
#RequestPart ("user") String u)
throws JsonParseException, JsonMappingException, IOException{
User user = new ObjectMapper().readValue(u, User.class) ;
user.setLogo(f.getBytes());
return userRepository.save(user);
}
User.java
#Entity
public class User {
#Id #GeneratedValue
private Long id ;
private String name ;
private String email ;
private String password ;
#Column(name="logo")
private byte[] logo;
#Column(name="file_name")
private String fileName ;
}
mainApplication.java
#SpringBootApplication
public class MyChebbaApplication {
public static void main(String[] args) {
SpringApplication.run(MyChebbaApplication.class, args);
}
#Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize("10240KB");
factory.setMaxRequestSize("10240KB");
return factory.createMultipartConfig();
}
}
Clien Side
component.html
<div class="container" >
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Register</div>
<div class="panel-body">
<form class="form-horizontal" #form="ngForm" (ngSubmit)="onSubmit(form)">
<div class="form-group">
<label for="name" class="control-label col-md-4">Nom Complet</label>
<div class="col-md-6">
<input id="name" type="text" name="name" #userName="ngModel" ngModel class="form-control" required>
</div>
</div>
<div class="form-group">
<label for="email" class="control-label col-md-4">E-mail Address</label>
<div class="col-md-6">
<input id="email" type="email" name="email" #userEmail="ngModel" ngModel class="form-control" required>
</div>
</div>
<!-- <div class="form-group">
<label for="phone" class="control-label col-md-4">Phone number</label>
<div class="col-md-6">
<input id="phone" type="phone" name="phone" #phone="ngModel" ngModel class="form-control" >
</div>
</div> -->
<div class="form-group">
<label for="password" class="control-label col-md-4">Password</label>
<div class="col-md-6">
<input id="password" type="text" name="password" #password="ngModel" ngModel class="form-control" required>
</div>
</div>
<div class="form-group">
<label for="file" class="control-label col-md-4">File Upload</label>
<div class="col-md-6">
<input
type="file"
name="file"
accept="image/*"
(change)="onFileSelected($event)"
ngModel class="form-control" >
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary"
[disabled]="form.invalid">
Register
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
component.ts
selectedFile: File = null ;
constructor(private userService: UserService) { }
ngOnInit() {
}
onFileSelected(event) {
console.log(event) ;
this.selectedFile = event.target.files[0] ;
}
onSubmit(form: any) {
let fd = new FormData() ;
const user = form.value ;
fd.append('user' , JSON.stringify(user)) ;
fd.append('file' , this.selectedFile ) ;
console.log(fd) ;
this.userService.register(fd )
.then((resp) => {
this.userService.logUserIn(resp) ;
}) ;
}
user.service.ts
register(fd: FormData ): Promise<UserData> {
return this.http.post(`${CONFIG.API_URL}/users`, fd)
.toPromise()
.then((response) => {
let token = response.json().token ;
let user = response.json() ;
let userData = new UserData(token, user) ;
this.router.navigate(['/users']);
return userData ;
});
}
this means that your JSON String u doesn't contain "file" field. In order to ignore missing fields please use this:
ObjectMapper mapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.readValue(u, User.class);
...
Good luck.
It means that User doesn't have a property file.
To solve that, just disable that config in applicatgion.properties.
pring.jackson.deserialization.fail-on-unknown-properties=true

Store null values in database while trying to save data using spring mvc angular js

angular js code
<body data-ng-app="myApp" data-ng-controller="UserController as userBean">
<form method="post" action="register" name="myForm">
<div class="form-group col-lg-7" >
<label for="username" class="control-label">First Name:</label>
<input type="text" data-ng-model="userBean.username" class="form-control" placeholder="Enter Firstname"/><br>
<label for="phone" class="control-label">Phone:</label>
<input type="text" data-ng-model="userBean.phone" class="form-control" placeholder="Enter phone no."/><br>
<label for="email" class="control-label">Email:</label>
<input type="text" data-ng-model="userBean.email" class="form-control" placeholder="Enter email"/><br>
<label for="address" class="control-label">Address:</label>
<input type="text" data-ng-model="userBean.address" class="form-control" placeholder="Enter address"/><br>
<label for="password" class="control-label">Password:</label>
<input type="password" data-ng-model="userBean.password" class="form-control" placeholder="Enter password"/><br>
</div>
<div class="form-group col-lg-7">
<button type="submit" data-ng-click="insertData()" class="btn btn-primary">Submit</button>
</div>
</form>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller("UserController", ['$scope', '$http', function($scope, $http, httpPostService) {
var self=this;
$scope.insertData = function()
{
alert($scope.userBean.username, $scope.userBean.phone, $scope.userBean.email);
$http({
method: "POST",
url: "register",
data:{
username: $scope.userBean.username,
phone: $scope.userBean.phone,
email: $scope.userBean.email,
address: $scope.userBean.address,
password: $scope.userBean.password}
}).then(function(response){
console.log(response.status);
console.log("in success");
}, function(response){
console.log(response.status);
console.log("in fail");
});
};
}]);
</script>
controller code
#RequestMapping(value="/register", method = RequestMethod.POST, consumes="application/json")
public #ResponseBody ModelAndView doRegister(#ModelAttribute #RequestBody UserBean userBean, BindingResult result)
{
if(!result.hasFieldErrors())
{
if(retrieveService.insert(userBean) != null)
{
System.out.println("done");
}
}
return new ModelAndView("redirect:/welcome");
}
}
I think a controller problem. userBean has null values to pass it to a controller. so kindly anyone helps me
It error also came
HTTP Status 415 – Unsupported Media Type The origin server is refusing to service the request because the payload is in a format not
supported by this method on the target resource.
Set content type JSON in your request headers like below.
$http({
method: "POST",
url: "register",
data:{
username: $scope.userBean.username,
phone: $scope.userBean.phone,
email: $scope.userBean.email,
address: $scope.userBean.address,
password: $scope.userBean.password},
headers: {'Content-Type': 'application/json'}
})
Use #JsonIgnore on the field which can have null values.

I am unable to render the JSON object that is being displayed as the response

The Previous issue of getting status 400 error has been resolved , I am able to retrieve the response as a JSON Object , I am here with attaching the modified code , The received JSON response is being stored in the JSON Object :
response_jsonObj , The output is in this format
0: { id: "value od id", name: "value of name" , field1: "value of field1" , field2: "value of field2" , ...}
0: { id: "value od id", name: "value of name" , field1: "value of field1" , field2: "value of field2" , ...} and so forth, I need to display this in the tabular format , I have followed the examples on stack overflow and am unable to replicate it , Any inputs are welcome .
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
this.state = { responsedata:[{"id":"","name":"","field1":"","field2":""}] }
}
handleSubmit(event) {
event.preventDefault();
const form = event.target;
const data = new FormData(form);
const arrayValue = [];
var i = 0;
console.log('Data from Form:',data);
for (let name of data.keys()) {
const input = form.elements[name];
const parserName = input.dataset.parse;
const parsedValue = data.get(name);
console.log('name',name);
console.log('parsedValue',parsedValue);
data.set(name, parsedValue);
arrayValue[i] = parsedValue;
i=i+1;
}
console.log('id:after get',arrayValue[0]);
console.log('field1:after get',arrayValue[2]);
console.log('field7:after get',arrayValue[8]);
var response_data = "";
var response_jsonObj ;
var txt = "";
var req = {"CustomerLookupRequest" : [{
"id":arrayValue[0],
"name": "",
"field1":arrayValue[2],
"field2":"",
"field3":"",
"field4":"",
"field5":"",
"field6":"",
"field7":arrayValue[8],
"field8":"",
"field9":"",
"fied10":"",
"field11":""
}]
};
console.log('req string :' + req);
fetch('API_URL', {
headers: {
'Accept': 'application/json, text/plain, application/xml, */*',
'Content-Type': 'application/json' ,
'Access-Control-Allow-Headers': 'Content-Type',
},
method: 'POST',
body: JSON.stringify(req)}
).then(function(response) {
if (response.status !== 200) {
console.log('Problem in fetching');
return;
}
response.text().then(function(data) {
console.log('Data in Console',data);
response_data = data;
console.log('Response Data',response_data);
response_jsonObj = JSON.parse(response_data);
console.log('Response JSON Object',response_jsonObj);
});
}).catch(error => this.setState({ error }));
}
render() {
return (
<div id = "id1">
<form onSubmit={this.handleSubmit}>
<label htmlFor="id">Enter id</label>
<input id="id" name="id" type="text" />
<label htmlFor="name">Enter Name</label>
<input id="name" name="name" type="text" />
<label htmlFor="Field1">Enter your Field1</label>
<input id="Field1" name="Field1" type="text" />
<label htmlFor="Field2">Enter your Field2</label>
<input id="Field2" name="Field2" type="text" />
<label htmlFor="Field3">Enter your Field3</label>
<input id="Field3" name="Field3" type="text" />
<label htmlFor="Field4">Enter your Field4</label>
<input id="Field4" name="Field4" type="text" />
<label htmlFor="Field5">Enter your Field5</label>
<input id="Field5" name="Field5" type="text" />
<label htmlFor="Field6">Enter your Field6</label>
<input id="Field6" name="Field6" type="text" />
<label htmlFor="Field7">Enter your Field7</label>
<input id="Field7" name="Field7" type="text" />
<label htmlFor="Field8">Enter your Field8</label>
<input id="Field8" name="Field8" type="text" />
<label htmlFor="Field9">Enter your Field9</label>
<input id="Field9" name="Field9" type="text" />
<label htmlFor="Field10">Enter your Field10</label>
<input id="Field10" name="Field10" type="text" />
<label htmlFor="Field11">Enter your Field11</label>
<input id="Field11" name="Field11" type="text" />
<button>Send data!</button>
</form>
</div>
);
}
}
export default App;
I'm not sure your fetch format is correct. Do this way.
fetch(POSTAPIURL, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
String1:"xyzabc",
String2:"ABCD"
})
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch( err => {
console.log(err);
});

MVC5 Mqsql Issue

After Update of Model from database in Entity Framework. Json Data not populate into textbox. when i use DeveloperTool i found a error "There is already an open DataReader associated with this Connection which must be closed first."[Error 505] Help me for resolve this problem.am using MySql in my project. When i use only one table in Model then i didn't get any error but when i update model then my project not working. If i add all the tables in Model then I face same problem.
Here is my code
Controller:-
// GET: Chains
public ActionResult Index()
{
ViewData["chain_name"] = new SelectList(db.chains, "code", "name");
return View(db.chains.ToList());
}
//Action Function callby javascript
[HttpPost]
public ActionResult Action(string code)
{
var query = from c in db.chains
where c.code == code
select c;
return Json(query);//Return Json Result
}
View:-
#using (#Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="form-group">
<label class="col-sm-2 control-label">
Select Chain
</label>
<div class="col-md-3">
#Html.DropDownList("ddlchainname", (SelectList)ViewData["chain_name"], new { onchange = "Action(this.value);", #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">
Chain Name
</label>
<div class="col-md-3">
#Html.TextBox("ChainName", null, new { #class = "form-control" })
</div>
<label class="col-sm-2 control-label">
Username
</label>
<div class="col-md-3">
#Html.TextBox("username", null, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">
Chain Code
</label>
<div class="col-md-3">
#Html.TextBox("ChainCode", null, new { #class = "form-control" })
</div>
</div>
</div>
}
<script type="text/javascript">
function Action(code) {
$.ajax({
url: '#Url.Action("Action", "Chains")',
type: "POST",
data: { "code": code },
"success": function (data) {
if (data != null) {
var vdata = data;
$("#ChainName").val(vdata[0].name);
$("#ChainCode").val(vdata[0].code);
$("#username").val(vdata[0].username);
}
}
});
}
Try this approach:
using (var db = new ChainEntities())
{
ViewData["chain_name"] = new SelectList(db.chains, "code", "name");
return View(db.chains.ToList());
}
This way you open the connection only once then dispose when done.
Sane for action:
[HttpPost]
public ActionResult Action(string code)
{
using (var db = new ChainEntities())
{
var query = from c in db.chains
where c.code == code
select c;
return Json(query);//Return Json Result
}
}