How to ensure user with image in mysql with angular6 - java

I'm trying to create new user. i want to send user information with image to mysql database. I'm sending a user object with form data .
this is my component.ts
subscribeUser() {
this.errorMessage = "";
if (this.subscribeForm.invalid) {
this.errorMessage = "cannot create user with empty fields";
return;
}
this.userService.createUser(this.user, this.selectedFile)
.subscribe(data => {
console.log(data);
this.router.navigate(['/login']);
}, error => {
console.log(error);
});
}
public onFileChanged(event) {
console.log(event);
this.selectedFile = event.target.files[0];
console.log(this.selectedFile);
}
this my service.ts
createUser(user: User,file : File) { let formdata: FormData = new FormData(); const userBlob = new Blob([JSON.stringify({"firstname":user.firstname,"lastname":user.lastname,"mail":user.mail,"password":user.password})],{ type: "application/json"});formData.append('file', file); formData.append('user', userBlob);return this.http.post<User>(AppSettings.APP_URL + "/users/new", formData,{responseType:'text' as 'json'});}
this is my controller.java
#PostMapping(value="/",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE,"multipart/form-data"}))
public ResponseEntity createUser(#RequestPart("file") MultipartFile file, #RequestPart("user") User user) throws IOException {
if(user == null){
return ResponseEntity.badRequest().body("cannot create user with empty fields");
}
User createdUser = userRepository.save(user);
return ResponseEntity.ok(createdUser);
}
this is my component.html
<form [formGroup]="subscribeForm" (ngSubmit)="subscribeUser()" novalidate>
<div class="form-group">
<label for="formGroupExampleInput">Nom</label>
<input type="text" class="form-control" id="firstname" [(ngModel)]="user.firstname" name="firstname" placeholder="Nom" formControlName="nom">
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Prénom</label>
<input type="text" class="form-control" id="lastname" [(ngModel)]="user.lastname" name="lastname" placeholder="Prenom" formControlName="prenom">
</div>
<div class="form-group">
<label for="formGroupExampleInput3">Email</label>
<input type="text" class="form-control" id="mail" [(ngModel)]="user.mail" placeholder="Email" name="mail" formControlName="mail" >
</div>
<div class="form-group">
<label for="formGroupExampleInput4">Password</label>
<input type="text" class="form-control" id="password" [(ngModel)]="user.password" placeholder="Password" formControlName="password" >
</div>
<div class="form-group">
<input type="file" [(ngModel)]="user.photo" (change)="onFileChanged($event)"></div>
<button class="btn btn-primary" type="submit">Register</button>
</form>
I get this error
"Content type 'application/octet-stream' not supported"
Thank you

Have you consider changing image type from File to BLOB.
And in REST Controller you can treat it as MultipartFile
Edit: the error you get
"Content type 'application/octet-stream' not supported"
I think it's your header mime type (see this mime type )

Related

Cannot get value from simple form user input in Spring boot application?

I'm trying to implement a login form in a Spring boot application. It has an email and a password field. The email field failed to get user input, here is the form:
<form th:action="#{/login}" method="get" th:object="${loginForm}" style="max-width: 600px; margin: 0 auto;">
<div class="m-3">
<div class="form-group row">
<label class="col-4 col-form-label">E-mail: </label>
<div class="col-8">
<input type="text" th:field="*{email}" name="q" class="form-control" required />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Password: </label>
<div class="col-8">
<input type="password" th:field="*{password}" class="form-control" required/>
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Log in</button>
</div>
</div>
</form>
Here is the controller:
#GetMapping("login")
public ModelAndView login(Model model, #RequestParam(name = "q", required = false) Optional<String> email) {
Optional<UserDto> aUser;
System.out.println(email);
if (email.isPresent()) {
aUser = userService.getAUserByEmail(email.get());
model.addAttribute("user", aUser);
var mv = new ModelAndView("user/user-list", model.asMap());
return mv;
} else {
model.addAttribute("loginForm", new LoginForm());
return new ModelAndView("/login/login-form", model.asMap());
}
}
I thought the #RequestParam(name = "q") and name="q" in html would do the job, but I always get Optional.empty for email. Any idea what's wrong here?
UPDATE:
From the answers I changed controller to this:
#GetMapping("login")
public ModelAndView login(Model model, LoginForm loginForm) {
Optional<UserDto> aUser;
if (loginForm.getEmail() != null) {
aUser = userService.getAUserByEmail(loginForm.getEmail());
model.addAttribute("user", aUser);
var mv = new ModelAndView("user/user-list", model.asMap());
return mv;
} else {
model.addAttribute("loginForm", new LoginForm());
return new ModelAndView("/login/login-form", model.asMap());
}
}
login-form.html to this:
<form th:action="#{/login}" method="get" th:object="${loginForm}" style="max-width: 600px; margin: 0 auto;">
<div class="m-3">
<div class="form-group row">
<label class="col-4 col-form-label">E-mail: </label>
<div class="col-8">
<input type="text" th:field="*{email}" class="form-control" required />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Password: </label>
<div class="col-8">
<input type="password" th:field="*{password}" class="form-control" required/>
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Log in</button>
</div>
</div>
</form>
I also have LoginForm.java like this
#Data
#AllArgsConstructor
#NoArgsConstructor
public class LoginForm {
private String email;
private String password;
}
but still not getting user email field input?
The way you have set up your form, it's mapping the value of your email input field to the property email (that's what th:field="*{email}" means) of an object called loginForm (that's what th:object="${loginForm}" means). Neither of these seem to be used or even exist in your login() method. You need to either change what you use in your controller to match what you have in your Thymeleaf template, or change your Thymeleaf template to actually reference what you are using in your controller.
The problem in your code is located under th:object="${loginForm}"
With this you inform spring to bind the data sent from the form into an object named loginForm.
So Spring actually expects the controller to be
#GetMapping("login")
public ModelAndView login(Model model, LoginForm loginForm) {
....
and inside LoginForm a field named email will contain the value sent from the form, as you have declared with <input type="text" th:field="*{email}" .... >
If you don't want the data to be bound into an object from Spring Mvc then
remove the th:object="${loginForm}"
use the
<input type="text" th:name="q" class="form-control" required />
and then the controller will receive the sent value as a query parameter
#GetMapping("login")
public ModelAndView login(Model model, #RequestParam(name =
"q", required = false) Optional<String> email) {

Spring MVC Login Form

I have created a simple login form that will redirect to the next page after submitting the form credentials. But it's not working fine.
here is my code:
Controller class:
#RequestMapping("/home")
public String showForm() {
return "home";
}
#RequestMapping(path = "/handleForm", method = RequestMethod.POST)
public String handleForm(HttpServletRequest request) {
String name = request.getParameter("username");
String pass = request.getParameter("password");
if (name != null && pass != null) {
if (name.equals("Twinkle") && pass.equals("twinkle123")) {
return "student-list";
} else {
return "home";
}
} else {
return "error";
}
}
home jsp file:
<div class="container mt-5">
<h3 class="text-center">Welcome, Login Here</h3>
<form action="handleForm" method="POST">
<div class="form-group">
<label for="username">User Name</label>
<input type="text" class="form-control"
id="username"
placeholder="Enter here"
name="username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" minlength="4"
maxlength="8" placeholder="Enter here" name="password">
</div>
<div class="container mt-5 text-center">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
How to fix it?

400 bad request when submitting form

I can't seem to figure out why I keep getting a 400 bad request. Before I got 400 bad request, the form had "id" instead of "name". When the form had "id" I got 200 but didn't update my database. Now, I get the error and nothing seems to be working.
Here's my controller:
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(MemberVO vo, Model model) {
System.out.println(vo);
logger.info("regist post...");
logger.info(vo.toString());
try {
mservice.insertMember(vo);
} catch (Exception e) {
e.printStackTrace();
}
return "/register_success";
}
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public void registrationGet(MemberVO vo, Model model) {
}
Here's my form:
<form role = "form" method ="post">
<div class="form-group">
<input type="email" class="form-control" name = "username" placeholder="Email" required/>
<span><i class="fa fa-envelope"></i></span>
</div>
<div class="form-group">
<input type="password" class="form-control" name = "password" placeholder="Password" required/>
<span><i class="fa fa-lock"></i></span>
</div>
<div class="form-group">
<input type="text" class="form-control" name = "firstname" placeholder="firstname" required/>
<span><i class="fa fa-user"></i></span>
</div>
<div class="form-group">
<input type="text" class="form-control" name = "lastname" placeholder="lastname" required/>
<span><i class="fa fa-user"></i></span>
</div>
<div class="form-group">
<input type="text" class="form-control" name = "phonenum" placeholder="Phone Number" required/>
<span><i class="fa fa-user"></i></span>
</div>
<div class="form-group">
<input type="text" class="form-control" name = "birthday" placeholder="Birthday, ex) 1986-06-08" required/>
<span><i class="fa fa-user"></i></span>
</div>
<div class="form-group">
<input type="text" class="form-control" name = "destination" placeholder="where would you like to go?" required/>
<span><i class="fa fa-user"></i></span>
</div>
<button type = "submit" class="btn btn-orange btn-block">Sign Up</button>
</form>
We can not tell you the exact problem as you have not attached your modal class MemberVO but you can check below.
1.There is no action attribute in your form.
2.Ensure that all the fields present in Modal class should also be present in the form with the same name.

Why the POST request becomes a GET request?

When I use jQuery's $.ajax() or $.post() method to send form information to server, the 'data' string is added to the end of the url. Why the POST request becomes a GET request? The form code shown below
<form role="form" class="form-horizontal">
<div class="box-body">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" required>
</div>
</div>
<div class="form-group">
<label for="hospital" class="col-sm-2 control-label">Hospital</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="hospital" name="hospital" required>
</div>
</div>
<div class="form-group">
<label for="url" class="col-sm-2 control-label">URL</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="url" name="url" required>
</div>
</div>
<div class="form-group">
<label for="version" class="col-sm-2 control-label">Version</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="version" name="version" required>
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<textarea class="form-control" id="description" name="description" rows="3" required></textarea>
</div>
</div>
</div>
<div class="box-footer text-center">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-primary" id="submitBtn">Submit</button>
</div>
</form>
Ajax code
$("#submitBtn").submit(function(event) {
event.preventDefault();
var info = {};
info.name = $("#name").val();
info.hospital = $("#hospital").val();
info.url = $("#url").val();
info.version = $("#version").val();
info.description = $("#description").val();
$.post("/nuts/add", JSON.stringify(info), function(data) {
console.log(data);
}, "json");
}
The url always like this
http://localhost:8080/nuts/add.html?name=1&hospital=1&url=1&version=1&description=1
My backend framework is Spring MVC, and the controller code shown below
#RestController
#RequestMapping(value = "/nuts/add", produces = {APPLICATION_JSON_VALUE})
public class AddNutsApi {
private MongoBasicDao<Nuts> mongoBasicDao;
#Autowired
public void setMongoBasicDao(MongoBasicDao<Nuts> mongoBasicDao) {
this.mongoBasicDao = mongoBasicDao;
}
#RequestMapping(value = "", produces = {APPLICATION_JSON_VALUE}, method = RequestMethod.POST)
public ResponseEntity<Void> addNutsPost(#RequestBody Nuts nuts) throws NotFoundException {
if (nuts.getName() != null && nuts.getHospital() != null && nuts.getUrl() != null && nuts.getVersion() != null && nuts.getDescription() != null) {
try {
Nuts _nuts = new Nuts();
_nuts.setName(new String(nuts.getName().getBytes("ISO-8859-1"), "UTF-8"));
_nuts.setHospital(new String(nuts.getHospital().getBytes("ISO-8859-1"), "UTF-8"));
_nuts.setUrl(new String(nuts.getUrl().getBytes("ISO-8859-1"), "UTF-8"));
_nuts.setVersion(new String(nuts.getVersion().getBytes("ISO-8859-1"), "UTF-8"));
_nuts.setDescription(new String(nuts.getDescription().getBytes("ISO-8859-1"), "UTF-8"));
_nuts.setCreationTime(new Date());
Integer mark = mongoBasicDao.getCollectionMark(Constant.COLLECTION_NUTS);
_nuts.setMark(mark);
mongoBasicDao.addObject(_nuts, Constant.COLLECTION_NUTS);
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
} else {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
}
I have added jackson's dependency(jackson-databind), and set the <mvc:annotation-driven/> in the Spring MVC configuration file. By the way, the DispatcherServlet's url-pattern is / .
Can anyone tell me where am I getting it wrong? Thanks a lot!
When you call JSON.stringify(info), you will get a JSON string , e.g. something like this:
{ "name": "1", "hospital": "1", "url": "1", "version": "1", "description": "1" }
You certainly will not get a query string like this:
?name=1&hospital=1&url=1&version=1&description=1
That should be your hint that the JavaScript code is not responsible for the GET request you see.
The problem is that you're binding the submit function wrong. $("#submitBtn").submit(...) doesn't do anything, because a <button type="submit"> doesn't fire any submit events. The <form> does.
What happens is that the JavaScript code is ignored, and clicking the Submit button will trigger a submit of the form, and since the <form> element doesn't have a method="post" attribute, the form will be submitted as a GET.
Solution: Bind the submit(...) to the <form>.

Why I am not able to insert and update?

<%#include file="../header.jsp" %>
<h1>Add Room</h1>
<form action="save" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Room Type</label>
<input type="text" name="roomType" placeholder="Enter Room Type" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Description</label>
<input type="text" name="roomDescription" placeholder="Enter Room Description" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Number</label>
<input type="number" name="roomNumber" placeholder="Enter Room Number" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Image</label>
<input type="file" name="file" placeholder="Select Room Image" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Image</label>
<input type="hidden" name="ro_id" value="${Room.ro_id}" placeholder="Select Room Image" required="required" class="form-control"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" value="submit">Save</button>
</div>
</form>
<%#include file="../footer.jsp" %>
Here is my edit jsp from where I update my database
Edit Room Jsp for updating for database using Room controller and I get
"Column Image"cannot be null
<%#include file="../header.jsp" %>
<h1>Edit Room</h1>
<form action="${SITE_URL}/admin/room/save" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Room Type</label>
<input type="text" name="roomType" value="${Room.room_type}" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Description</label>
<input type="text" name="roomDescription" value="${Room.room_description}" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Number</label>
<input type="number" name="roomNumber" value="${Room.room_number}" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Image</label>
<input type="file" name="file" link src="D:/Hotels/uploadedImage/${Room.image}" required="required" class="form-control" />
</div>
<form:hidden path="${Room.ro_id}" />
<input type="text" value="${Room.ro_id}" name="id"/>
<div class="form-group">
<button type="submit" class="btn btn-success" value="editroom/ro_id" >Save</button>
</div>
</form>
<%#include file="../footer.jsp" %>
When I try to update the page i get Column"image" cannot be null
and when I try to add it "Required int parameter #id is not present
/**
*
* #author
*/
#Controller
#RequestMapping(value = "/admin/room")
public class Roomcontroller {
#Autowired
private RoomService roomService;
#RequestMapping(method = RequestMethod.GET)
public String index(ModelMap map) throws SQLException {
map.addAttribute("Room", roomService.getAll());
return "admin/room/index";
}
#RequestMapping(value = "/addroom", method = RequestMethod.GET)
public String addRoom() throws SQLException {
return "admin/room/addroom";
}
#RequestMapping( value = "/editroom/{ro_id}", method = RequestMethod.GET )
public #ResponseBody ModelAndView edit(#PathVariable("ro_id") int ro_id) throws SQLException {
ModelAndView mv = new ModelAndView("admin/room/editroom");
mv.addObject("Room", roomService.getById(ro_id));
return mv;
}
#RequestMapping(value = "/deleteroom/{ro_id}", method = RequestMethod.GET)
public String delete(#PathVariable("ro_id") int ro_id) throws SQLException {
roomService.delete(ro_id);
return "redirect:/admin/room";
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#RequestParam("roomType") String roomType,#RequestParam("id") int id,
#RequestParam("roomDescription") String roomDescription, #RequestParam("roomNumber") int roomNumber
,#RequestParam("file") MultipartFile multipartFile,HttpServletRequest req) throws SQLException, IOException {
Room attributes
Room room = new Room();
room.setRo_id(id);`
room.setRoom_type(roomType);
room.setRoom_description(roomDescription);
room.setRoom_number(roomNumber);
// TO DO : Save room, fetch the id of saved room and set it through
// setter in above object.
System.out.println(room.getRo_id());
if(room.getRo_id()==0){
System.out.println(room.getRo_id());
String serverRootPath = req.getServletContext().getRealPath("");
System.out.println(serverRootPath);
// You can change the directory.
File roomImageDirectory = new File("D:\\Hotels\\uploadedImages");
if (!roomImageDirectory.exists()) {
roomImageDirectory.mkdirs();
}
String[] fileNameToken = multipartFile.getOriginalFilename().split("\\.");
// You can change file name to be saved.
String newFileName = "room-" + room.getRoom_number() + "." + fileNameToken[fileNameToken.length - 1];
File roomImage = new File(roomImageDirectory, "/" + newFileName);
roomImage.createNewFile();
multipartFile.transferTo(roomImage);
room.setImage(newFileName);
roomService.insert(room);
}
else
{
roomService.update(room);
}
return "redirect:/admin/room";
}
}

Categories