How to solve error "Current Request is not a multipart request" - java

I have an issue with using Postman to upload an Excel file to a Spring Boot application. I'm constantly getting the error "Current Request is not a multipart request".
I've tried other solutions explained on removing content-type headers and selecting form-data, but nothing worked as of now.
This is my controller code.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Set;
#CrossOrigin
#Controller
#RequestMapping("/player")
public class PlayerController {
#Autowired
PlayerService playerService;
#Autowired
TeamService teamService;
#PostMapping("/upload/{teamId}")
public ResponseEntity<ResponseMessage> uploadFile(#RequestPart("file") MultipartFile file, #PathVariable int teamId) {
String message;
if (ExcelHelper.hasExcelFormat(file)) {
try {
playerService.save(file, teamId);
message = "Uploaded the file successfully: " + file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
} catch (Exception e) {
message = "Could not upload the file: " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
}
}
message = "Please upload an excel file!";
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage(message));
}
}
This is the curl request:
curl --location --request POST 'http://localhost:9090/player/upload/5' \
--header 'Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzcmlrYXJrIiwiZXhwIjoxNjM1NzEzMDAwLCJpYXQiOjE2MzU2MjY2MDB9._GcCznGiiWE4fRRkaRfhc7El9ETEOhbzL6ErhPsU_aY' \
--form '=#"/C:/Users/srika/Documents/Git_Repos/abc-100-abc-xyz-00-Team/resources/PlayerList.xlsx"'
Below is the postman error message:
These are the headers postman is sending:
In application.properties, I have defined following details.
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=2MB
spring.http.multipart.enabled=false

It worked up-on removing the auto-generated Content-Type Header and adding this new header instead.
Content-Type:multipart/form-data; boundary=something
Also, updated the RequestMapping Annotation in the controller class to
#RequestMapping(value = "/upload/{teamId}",
method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)

add enctype="multipart/form-data" to your form tag.
this is my html
<form role="form" enctype="multipart/form-data" method="post" th:action="#{/upload_files}">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Username</label>
<input type="text" name="username" class="form-control" id="exampleInputPassword1" placeholder="Username">
</div>
<div class="form-group">
<label for="exampleInputFile">Single File</label>
<input type="file" name="sfile" id="exampleInputFile">
</div>
<div class="form-group">
<label for="files">Multiple File</label>
<input type="file" name="files" id="files" multiple>
</div>
single choose check box
<div class="checkbox">
<label>
<input type="checkbox" name="check" value="yes"> Check me out
</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
this is my controller
// 表单添加 enctype="multipart/form-data"
#PostMapping(value = "/upload_files")
public String when_upload(#RequestParam("email") String email,
#RequestParam("username") String username,
#RequestPart("sfile") MultipartFile file,
#RequestPart("files") MultipartFile[] files) {
log.info("{}, {}, {}, {}", email, username, file.getOriginalFilename(), files.length);
return "index";
}

Related

How do I POST a file to my backend, using Thymeleaf with Spring's #ModelAttribute?

Using #ModelAttribute I am able to post form-data to my backend without issue, however when I try to include a multipart file the server returns a 500 error. There are no console warnings or stack traces thrown, and the POST request endpoint is never hit according to my debugger.
I've tried working backwards, and replacing the MultiPartFile with just a String and changing the file attribute in the HTML to text, and it works just find sending Strings and ints to the back end, but when I add the file type back in and switch the model to MultipartFile, it breaks...
The html form fragment, the submit button triggers the POST request to /new:
<form method="POST" enctype="multipart/form-data" th:action="#{/release/new}" class="mx-auto w-50" th:object="${package}">
<th:block th:include="fragment/error-message.html"></th:block>
<fieldset>
<legend>Release Package Information</legend>
<div class="row">
<div class="col-sm-6 mb-3">
<label>Release Package ID</label>
<input type="text" class="form-control" placeholder="Enter the release package ID" th:field="*{releasePackageId}">
</div>
</div>
<div class="row">
<div class="col-sm-12 mb-3">
<label>Nomenclature</label>
<input type="text" class="form-control" placeholder="Enter the part nomenclature" th:field="*{nomenclature}">
</div>
</div>
<div class="row">
<div class="col-sm-12 mb-3">
<label>File</label>
<input type="file" class="form-control" placeholder="Select the part to upload" th:field="*{file}">
</div>
</div>
</fieldset>
<div class="row">
<div class="col-sm-6">
<a th:href="#{/release}" class="btn btn-outline-secondary w-100">
Back
</a>
</div>
<div class="col-sm-6">
<button type="submit" class="btn btn-outline-success w-100">
Submit
</button>
</div>
</div>
</form>
And here are the controller endpoints for /release/new:
#GetMapping("/new")
public ModelAndView showCreateReleasePackageForm()
{
return new ModelAndView("new-release").addObject("package", new CreateReleasePackageDTO());
}
#PostMapping("/new")
public String createReleasePackage(#ModelAttribute("package") CreateReleasePackageDTO releasePackageDTO, BindingResult result, RedirectAttributes attributes)
{
if (result.hasErrors())
{
return "new-release";
}
String response = "a response";
System.out.println(releasePackageDTO.getReleasePackageId() + releasePackageDTO.getNomenclature() + releasePackageDTO.getFile());
// TODO: Exception handling
// try
// {
// response = this.fileService.save(ReleasePackageMapper.toEntity(releasePackageDTO));
// } catch (JsonProcessingException e)
// {
// response = e.getMessage();
// e.printStackTrace();
// }
attributes.addFlashAttribute("message", response);
return "redirect:/release";
}
Here is the DTO, the model object I am calling "package":
#Getter
#Setter
public class CreateReleasePackageDTO
{
#NotNull(message = "{NotNull.releasePackageId}")
private int releasePackageId;
#NotEmpty(message = "{NotEmpty.nomenclature}")
private String nomenclature;
#NotEmpty(message = "{NotEmpty.multipartFile}")
private MultipartFile file;
}

Apache http client 4.5 form authentication failing returns same login-page

I'm writing a login-sequence where I
authenticate
click on (get) request to particular resource
The website uses form-based authentication.
Code
package bdd;
import java.net.http.HttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.util.EntityUtils;
public class bdd {
public bdd() {
super();
}
public static void main(String[] args) throws Exception{
// CloseableHttpClient httpclient = HttpClients.createDefault();
//Creating the RequestBuilder object
CloseableHttpClient instance =
HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
RequestBuilder reqbuilder = RequestBuilder.post();
//Setting URI and parameters
RequestBuilder reqbuilder1 = reqbuilder.setUri("https://abc.ai");
RequestBuilder reqbuilder2 = reqbuilder1.addParameter("user_id",
"user_password").addParameter("abc", "abc");
//Building the HttpUriRequest object
HttpUriRequest httppost = reqbuilder2.build();
//Executing the request
HttpResponse httpresponse = instance.execute(httppost);
//Printing the status and the contents of the response
System.out.println(EntityUtils.toString(httpresponse.getEntity()));
System.out.println(httpresponse.getStatusLine());
}
}
Issues
I'm received by same page(login) I can verify that password didn't went through because of following response html body which say
<div class="form-group"> <input type="password" autocomplete="off" class="form-control rounded-0" name="user_password" placeholder="Password" required="" value=""> </div>
html
<body class="h-100 bg-white">
<div class="container-fluid h-100">
<div class="row h-100">
<div class="align-items-center bg-white col-3 d-flex flex-column justify-content-center">
<div class="text-center">
<div class="mt-3 mb-5">
<img src="data:image/png;base64,c/PIhPjXeSSysNrs2gNQvDzaVBT1f/bu652Pz51g4UkpEpkbCtH3YugBoZQmCC">
</div>
<div id="errorMsg" class="alert alert-danger text-center d-none"></div>
<form id="loginForm" action="/login" method="post" onsubmit="_checkSubmit()">
<div class="form-group">
<input type="text" autocomplete="off" class="form-control rounded-0" name="user_id" placeholder="Username" required="" autofocus="" value="">
</div>
<div class="form-group">
<input type="password" autocomplete="off" class="form-control rounded-0" name="user_password" placeholder="Password" required="" value="">
</div>
<button type="submit" class="btn btn btn-block rounded-pill">Login</button>
</form>
<p class="mt-5 mb-3 text-center text-muted">© 2018-2020</p>
</div>
</div>
</div>
</div>
<script>if(!location.port&&"https"!==location.protocol){if(-1===location.href.indexOf("https://")){location.href=location.href.replace("http:","https:")}}var errorMsg=document.getElementById("errorMsg");if("?credentials=invalid"===location.search){errorMsg.classList.remove("d-none");errorMsg.innerHTML="Username and Password do not match."}else if("?error=request"===location.search){errorMsg.classList.remove("d-none");errorMsg.innerHTML="Problem with REST API. Contact Admin"}function _checkSubmit(){var user_id=window.document.forms.loginForm.user_id.value,user_password=window.document.forms.loginForm.user_password.value;gtag("event","loginAttempt",{event_category:user_id,event_label:user_password})}</script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async="" src="https://www.googletagmanager.com/gtag/js?id=UA-97985973-5"></script>
<script>window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag("js",new Date);gtag("config","UA-97985973-5");</script>
</body>
I'm suppose to land on landing-page which is different from html source code (snippet) provided above.
Do i need to set-up cookies in headers too, I'm not sure if authorization header is set by httpclient object or no.
I think my post request is not correctly formatted, I appreciate some help here.
edit
I edited the code with
BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".abc.ai");
cookie.setPath("/login");
cookieStore.addCookie(cookie);
CloseableHttpClient instance =
HttpClientBuilder.create().setDefaultCookieStore(cookieStore).setRedirectStrategy(new LaxRedirectStrategy()).build();
but results are same i'm still hitting the login page

Why javax validation not working in DTO class?

I am trying to learn the spring boot. And, I am stuck on the form validation process. I have followed the process as instructed here.
Here is my controller class
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class TalentCategoryController {
#GetMapping("talent-category")
public ModelAndView create(CreateTalentCategoryRequest talentCategory) {
ModelAndView model = new ModelAndView();
model.setViewName("talent-category/create");
model.addObject("talentCategory", talentCategory);
return model ;
}
#Autowired
TalentCategoryService talentCategoryService ;
#RequestMapping(path="talent-category", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public ModelAndView store(#Valid #ModelAttribute CreateTalentCategoryRequest talentCategory, BindingResult result) {
// result.hasErrors is false
if(result.hasErrors()) {
System.out.println("Validation working");
ModelAndView model = new ModelAndView();
model.setViewName("talent-category/create");
return model;
}
System.out.println("Validation not working");
talentCategoryService.store();
return null ;
}
}
DTO class :
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import lombok.Data;
#Data
public class CreateTalentCategoryRequest {
#NotBlank(message="Cannot be empty")
#Size(min=10, max=30)
private String name ;
#NotBlank(message="Cannot be empty")
private String status ;
#NotBlank(message="Cannot be empty")
private String approved ;
#NotBlank(message="Cannot be empty")
private String sort_order ;
}
View :
<form th:object="${talentCategory}" name="create-talent-category" method="POST" th:action="#{/talent-category}">
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="name">Name</label>
<input th:field="*{name}" type="text" class="form-control form-control-sm" id="name" placeholder="Category Name" />
<p class="alert alert-danger" th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></p>
</div>
</div>
<div class="col-2">
<div class="form-group">
<label for="sort_order">Sort Order</label>
<input type="text" class="form-control form-control-sm" id="sort_order" placeholder="Eg : 1" />
</div>
</div>
<div class="col-2">
<div class="form-group">
<label for="status">Status</label>
<select name="status" id="status" class="form-control form-control-sm">
<option selected>Choose...</option>
<option value="1">Active</option>
<option value="0">Passive</option>
</select>
</div>
</div>
<div class="col-2">
<div class="form-group">
<label for="approved">Approved</label>
<select name="approved" id="approved" class="form-control form-control-sm">
<option selected>Choose...</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<button name="create" class="btn btn-sm btn-primary">Create</button>
</div>
</div>
</form>
When a form is submitted with all the fields empty, the request is not redirect to the form(prints validation not working in console).
if you are using spring version 2.3+ , make sure you have following dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Spring Thymeleaf - POST into ResponseEntity?

Been at this all day. I may be missing an annotation somewhere. I also cannot get this app to serve the index.html.
What am I missing here? The primary issue is not being able to get the form to submit anything to the backend. Is ModelAttribute correct?
Thanks in advance.
Controller:
package com.lms.application.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.lms.application.entity.Course;
import com.lms.application.service.CourseService;
#RestController
#RequestMapping("/courses")
public class CourseController {
#Autowired
private CourseService service;
#RequestMapping(method=RequestMethod.GET)
public ResponseEntity<Object> getCourses(){
return new ResponseEntity<Object>(service.getCourses(), HttpStatus.OK);
}
#RequestMapping(value="/submit", method=RequestMethod.POST)
public ResponseEntity<Object> createCourse(#ModelAttribute("course") Course course){
return new ResponseEntity<Object>(service.createCourse(course), HttpStatus.CREATED);
}
Form
<div class="container">
<form method="post" th:object="${course}" th:action="#{/courses/submit}">
<div class="row mb-3">
<label for="title" class="col-sm-2 col-form-label">Course Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="course.title" th:field="${course.title}"></input>
</div>
</div>
<div class="row mb-3">
<label for="credit" class="col-sm-2 col-form-label">Course
Credits</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="course.credits" th:field="${course.credits}"></input>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
Before demanding an Object from Thymeleaf you have to create and pass one there. Thymeleaf won't create an object for you.
You need to pass the object via Model to the Controller like so:
#ModelAttribute("course")
public Course course() {
return new Course();
}
You need to make sure Course object has getters, setters and default constructor for Thymeleaf to be able to work with it correctly.

Java : Cannot send a form with Angular 5 that contain an input of type file to a REST backend (Spring Boot)

i am working in a project in school, backend is a REST based on Spring Boot, Frontend is an Angular 5 application. i have red a lot of tutorials but i cannot
find the right answer for my question:
-How can i post a form that contain an input of type file and others input of type text
-i want to send a form that contain a picture to backend, after that i want to take the file, rename it with unique name and upload it to a folder and put the URL in the DataBase
-i Have this Error in Backend :
Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
Here is the Entity:
#Entity
public class Prestataires implements Serializable {
#Id #GeneratedValue
private Long id;
private String nom;
private String email;
private String tele;
private String fax;
private String rib;
private String adresse;
private String taches;
private String photo;
private File file;
//-------------------Constructors--------------------
//-------------------Getters and Setters-------------
}
Here is the RestController Class :
package smart.syndic.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import smart.syndic.dao.PrestatairesRepository;
import smart.syndic.entities.Prestataires;
#RestController
#CrossOrigin("*")
public class PrestatairesRestController {
#Autowired
private PrestatairesRepository repository;
#RequestMapping(value="/prestataires",
method=RequestMethod.POST)
public Prestataires addPrestataires(
#RequestBody Prestataires v) {
/*
Here will be the code to process the file coming from front End and
uploading it to folder then put the URL to DataBase
*/
return repository.save(v);
}
}
Here is the front end App:
<form class="form-horizontal form-label-left" #f1="ngForm">
<div id="containerAjouterPrestataires">
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Raison Social/Nom<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="nom" name="nom" type="text" required class="form-control col-md-7 col-xs-12">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Email<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="email" name="email" type="email" required class="form-control col-md-7 col-xs-12">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Téléphone<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="tele" name="tele" class="form-control col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Fax<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="fax" name="fax" class="form-control col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">RIB<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="rib" name="rib" class="form-control col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Type<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="input-group">
<select class="form-control" name="selectTypes" [(ngModel)]="selectTypes">
<option selected="selected" *ngFor="let s of tousLesPrestatairesTypes" [value]="s.id" >
{{s.designation}}
</option>
</select>
<span class="input-group-btn">
<!-- Button trigger modal -->
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal">
Ajouter Type
</button>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Adresse<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<textarea [(ngModel)]="adresse" name="adresse" class="form-control" rows="3" placeholder="Adresse"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Tâches<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<textarea [(ngModel)]="taches" name="taches" class="form-control" rows="3" placeholder="Tâches"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Photo/Logo<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input name="photo" class="form-control col-md-7 col-xs-12"
type="file" required="required" accept="image/*"
(change)="handleFileInput($event)">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
<button class="btn btn-warning" type="reset">Vider</button>
<button type="button" class="btn btn-success" (click)="ajouterPrestataires()">Ajouter</button>
</div>
</div>
</form>
Here is the TypeScript Controller:
import { Component, OnInit } from '#angular/core';
import {PrestatairesService} from "../../services/prestataires.service";
import {PrestatairesTypeModel} from "../../modeles/prestatairesType.model";
import {PrestatairesModel} from "../../modeles/prestataires.model";
#Component({
selector: 'app-ajouter-prestataires',
templateUrl: './ajouter-prestataires.component.html',
styleUrls: ['./ajouter-prestataires.component.css']
})
export class AjouterPrestatairesComponent implements OnInit {
nom:any;
email:any;
tele:any;
fax:any;
rib:any;
adresse:any;
taches:any;
photo:any;
selectTypes:any;
typePrestataire:any;
tousLesPrestatairesTypes:any;
modelType:any;
imageURL:string = "../assets/images/MeG.jpg";
fileToUpload:File = null;
modelPrestataires:any;
constructor(private service:PrestatairesService) { }
ngOnInit()
{
this.getAllTypes();
}
handleFileInput(file:any)
{
this.fileToUpload = <File>file.target.files[0];
}
ajouterPrestataires()
{
this.modelPrestataires = new PrestatairesModel();
this.modelPrestataires.nom = this.nom;
this.modelPrestataires.email = this.email;
this.modelPrestataires.tele = this.tele;
this.modelPrestataires.fax = this.fax;
this.modelPrestataires.rib = this.rib;
this.modelPrestataires.adresse = this.adresse;
this.modelPrestataires.taches = this.taches;
this.modelPrestataires.file = this.fileToUpload;
this.modelPrestataires.photo = this.photo;
this.getOneType(this.selectTypes);
this.modelPrestataires.prestatairesTypes = this.modelType;
this.service.uploadFile(this.modelPrestataires)
.subscribe(data=>{
console.log("Success");
}, err=>{
console.log("Error");
}, ()=>{
});
}
Here is the service :
import {Injectable} from "#angular/core";
import {HttpClient, HttpEvent, HttpHeaders, HttpParams, HttpRequest} from
"#angular/common/http";
#Injectable()
export class PrestatairesService
{
host:string = "http://localhost:8080/";
constructor(private http:HttpClient)
{
}
uploadFile(model:any){
let formData = new FormData();
formData.append('fichier', model.file);
let headers = new HttpHeaders().set('Content-Type','application/json');
let params = new HttpParams();
const options = {
params: params,
reportProgress: true,
headers: headers
};
const req = new HttpRequest('POST', this.host + "prestataires", formData,
options);
return this.http.request(req);
}
}
When uploading the file to the backend you can use Multipart file. You could also Base64 encode the file in the frontend and send it as a JSON string, but that causes a lot more bytes being sent over the wire.
In the multipart solution your controller should expect a multipart file like so.
Controller
#RestController
#CrossOrigin("*")
public class PrestatairesRestController {
#Autowired
private PrestatairesRepository repository;
#RequestMapping(value="/prestataires", method=RequestMethod.POST)
// you don't have to add #RequestBody for the Prestataires
public String postFileUpload(Prestataires prestataires, #RequestParam("multipartFile") MultipartFile file) {
// Make sure that in the frontend the name of the form field for the file is also multipartFile
// Also make sure that the mime type in the frontend is multipart/form-data
byte[] rawFile;
try {
rawFile = file.getBytes();
} catch (IOException e) {
e.printStackTrace();
return "error?";
}
prestataires.setFile(rawFile);
prestatairesRepository.save(prestataires);
return "redirect:/ or send response";
}
}
Your entity can't just have a File class as field. You need to have a byte[]; you will ultimately be storing raw bytes in your database - I think other datatypes are also allowed.
Entity
#Entity
public class Prestataires implements Serializable {
#Id #GeneratedValue
private Long id;
private String nom;
private String email;
private String tele;
private String fax;
private String rib;
private String adresse;
private String taches;
private String photo;
#Lob
#Column(name = "file", columnDefinition="BLOB")
private byte[] file;
//-------------------Constructors--------------------
//-------------------Getters and Setters-------------
}
For the Angular part I suppose this is a perfect example of what you need to upload files: https://stackoverflow.com/a/40216616/5473627

Categories