I am trying to invoke a webservice from java spring controller. Below is the code
private void storeImages(MultipartHttpServletRequest multipartRequest) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://localhost:8080/dream/storeimages.htm");
MultipartFile multipartFile1 = multipartRequest.getFile("file1");
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("file1",
new ByteArrayBody(multipartFile1.getBytes(),
multipartFile1.getContentType(),
multipartFile1.getOriginalFilename()));
postRequest.setEntity(multipartEntity);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
}
Above is just partial code. I am trying to determine how to retrieve this on the server side. On the server side i have the following Spring controller code
#RequestMapping(value = "/storeimages.htm", method = RequestMethod.POST)
public ModelAndView postItem(HttpServletRequest request,
HttpServletResponse response) {
logger.info("Inside /secure/additem/postitem.htm");
try {
// How to get the MultipartEntity object here. More specifically i
// want to get back the Byte array from it
} catch (Exception ex) {
ex.printStackTrace();
}
return new ModelAndView("success");
}
I executed this code and my control is going to the server side. But i am stuck on how to get back the byte array from the multipartentity object.
Edited requirement:
Here is the requirement. User uploads the images from website (This is done and working) The control goes to the Spring controller after form submit (This is done and working) In Spring controller I am using Multipart to get the content of the form. (This is done and working) Now i want to call a webservices which will send the image byte array to image server.(This needs to be done) On the image server, i want to receive this webservice request get all the fields from HTTPServlerRequest, store the images and return(This needs to be done)
Finally resolved it. Here is what worked for me.
Client side
private void storeImages(HashMap<String, MultipartFile> imageList) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://localhost:8080/dream/storeimages.htm");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
Set set = imageList.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
String fileName = (String)me.getKey();
MultipartFile multipartFile = (MultipartFile)me.getValue();
multipartEntity.addPart(fileName, new ByteArrayBody(multipartFile.getBytes(),
multipartFile.getContentType(), multipartFile.getOriginalFilename()));
}
postRequest.setEntity(multipartEntity);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
logger.info("Webservices output - " + output);
}
httpClient.getConnectionManager().shutdown();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Server side
#RequestMapping(value = "/storeimages.htm", method = RequestMethod.POST)
public void storeimages(HttpServletRequest request, HttpServletResponse response)
{
logger.info("Inside /secure/additem/postitem.htm");
try
{
//List<Part> formData = new ArrayList(request.getParts());
//Part part = formData.get(0);
//Part part = request.getPart("file1");
//String parameterName = part.getName();
//logger.info("STORC IMAGES - " + parameterName);
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Set set = multipartRequest.getFileMap().entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
String fileName = (String)me.getKey();
MultipartFile multipartFile = (MultipartFile)me.getValue();
logger.info("Original fileName - " + multipartFile.getOriginalFilename());
logger.info("fileName - " + fileName);
writeToDisk(fileName, multipartFile);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public void writeToDisk(String filename, MultipartFile multipartFile)
{
try
{
String fullFileName = Configuration.getProperty("ImageDirectory") + filename;
FileOutputStream fos = new FileOutputStream(fullFileName);
fos.write(multipartFile.getBytes());
fos.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
In my project, we used to use MultipartParser from com.oreilly.servlets to handle HttpServletRequests corresponding to multipart requests, as follows:
// Should be able to handle multipart requests upto 1GB size.
MultipartParser parser = new MultipartParser(aReq, 1024 * 1024 * 1024);
// If the content type is not multipart/form-data, this will be null.
if (parser != null) {
Part part;
while ((part = parser.readNextPart()) != null) {
if (part instanceof FilePart) {
// This is an attachment or an uploaded file.
}
else if (part instanceof ParamPart) {
// This is request parameter from the query string
}
}
}
Hope this helps.
Instead of doing all that by hand, you can use Springs Mutlipart support
The controller can work like this (This example use a command object to store additional user inputs -- (this is an example from an working project)).
#RequestMapping(method = RequestMethod.POST)
public ModelAndView create(#Valid final DocumentCreateCommand documentCreateCommand,
final BindingResult bindingResult) throws IOException {
if (bindingResult.hasErrors()) {
return new ModelAndView("documents/create", "documentCreateCommand", documentCreateCommand);
} else {
Document document = this.documentService.storeDocument(
documentCreateCommand.getContent().getBytes(),
StringUtils.getFilename(StringUtils.cleanPath(documentCreateCommand.getContent().getOriginalFilename())));
//org.springframework.util.StringUtils
return redirectToShow(document);
}
}
#ScriptAssert(script = "_this.content.size>0", lang = "javascript", message = "{validation.Document.message.notDefined}")
public class DocumentCreateCommand {
#NotNull private org.springframework.web.multipart.MultipartFile content;
Getter/Setter
}
To enable Spring Multipart support you need to configure some stuff:
web.xml (Add org.springframework.web.multipart.support.MultipartFilter after CharacterEncodingFilter and before HttpMethodFilter)
<filter>
<filter-name>MultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
<!-- uses the bean: filterMultipartResolver -->
</filter>
<filter-mapping>
<filter-name>MultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
In your Spring Configuration for the CORE (not MVC Servlet) of your application add this
<!-- allows for integration of file upload functionality, used by an filter configured in the web.xml -->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="filterMultipartResolver" name="filterMultipartResolver">
<property name="maxUploadSize" value="100000000"/>
</bean>
Then you also need the commons fileupload libary, because the Spring MultipartFile is just some kind of Addapter
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
For some more Details:
#See Spring Reference, Chapter 15.8 Spring's multipart (fileupload) support
to deal with spring files to the controller. you need to indicate, in your app-config.xml as follows:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
and treat code as follows
MultipartEntityBuilder paramsBuilder = MultipartEntityBuilder.create();
Charset chars = Charset.forName("UTF-8");
paramsBuilder.setCharset(chars);
if (null != obj.getFile()){
FileBody fb = new FileBody(obj.getFile());
paramsBuilder.addPart("file", fb);
}
and this for red multipart
private File getFile(MultipartFile file) {
try {
File fichero = new File(file.getOriginalFilename());
fichero.createNewFile();
FileOutputStream fos = new FileOutputStream(fichero);
fos.write(file.getBytes());
fos.close();
return fichero;
} catch (Exception e) {
return null;
}
}
I hope this helps.
Related
I'm currently writing a post API that gets a list of invoices number and then calls another API with resttamplate to obtain a pdf for every invoice number after that I concatenate all these pdf files to one file and return this file as a response, the problem here that there are invoices have an invalid invoice number so when I send this invoice number to the rest API can't get pdf so I want to get the failed invoices and send them back to the caller of my rest API, how to return pdf of the successful invoice and JSON object that contain a list of failed invoices number. Thanks in advance
that's my postApi
#PostMapping(value = "/gen-report")
public ResponseEntity<byte[]> generateReport(
#RequestHeader(value = HttpHeaders.AUTHORIZATION) String headerAuthorization) {
byte[] res = null;
List<String> failedInvoices = new ArrayList<>();
ResponseEntity<byte[]> response = null;
ArrayList<RequestParameters> requests = new ArrayList<>();
RequestParameters rp1 = new RequestParameters("360", "3600382368", "N");
RequestParameters rp2 = new RequestParameters("360", "3600382367", "N");
requests.add(rp1);
requests.add(rp2);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
List<byte[]> responses = new ArrayList<>();
for (RequestParameters parameter : requests) {
MultiValueMap<String, String> map = mobileOrderReportService.genrateReportService(parameter);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
response = null;
byte[] content = null;
content = requestReportByInvoiceNumber(entity);
if (content != null) {
responses.add(content);
} else {
failedInvoices.add(parameter.getOrderNum());
}
}
try {
res = mergePDF(responses);
} catch (DocumentException ex) {
Logger.getLogger(MobileOrderReportController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MobileOrderReportController.class.getName()).log(Level.SEVERE, null, ex);
}
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "pdf1.pdf";
headers.add("content-disposition", "inline;filename=" + filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
response = new ResponseEntity<byte[]>(res, headers, HttpStatus.OK);
return response;
}
this method returns the byte[] with the successful invoice or null with the failed invoice
public byte[] requestReportByInvoiceNumber(HttpEntity<MultiValueMap<String, String>> entity) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<byte[]> response = null;
try {
response = restTemplate.exchange(mobileOrderReportService.getUrl(), HttpMethod.POST, entity,
byte[].class);
byte[] content = response.getBody();
return content;
} catch (RestClientException ex) {
logger.error("request to UReport failed in requestReportByInvoiceNumber method !...");
return null;
}
}
method merge pdf and return one pdf
public byte[] mergePDF(List<byte[]> pdfFilesAsByteArray) throws DocumentException, IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
Document document = null;
PdfCopy writer = null;
for (byte[] pdfByteArray : pdfFilesAsByteArray) {
try {
PdfReader reader = new PdfReader(pdfByteArray);
int numberOfPages = reader.getNumberOfPages();
if (document == null) {
document = new Document(reader.getPageSizeWithRotation(1));
writer = new PdfCopy(document, outStream); // new
document.open();
}
PdfImportedPage page;
for (int i = 0; i < numberOfPages;) {
++i;
page = writer.getImportedPage(reader, i);
writer.addPage(page);
}
} catch (Exception e) {
e.printStackTrace();
}
}
document.close();
outStream.close();
return outStream.toByteArray();
}
You already tagged "Multipart", which could be a solution. You're currently not sending one but just a byte array i.e. a file. With a multipart response, you could indeed have multiple (or in your case 2) parts:
Part with the merged PDF
List of failed invoice numbers either as plain text, JSON, or however you would like to send it.
A multipart response looks like this https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html (scroll down to the example)
An easier and "dirtier" way would be, to just include the faulty invoice numbers in your header response. You can define custom headers, so feel free to name it as you wish.
Either way, your client needs to be adapted, either by being able to read a multipart response (for which you need to write an HttpMessageConverter if your client isn't communicating reactively (Webflux)) or by reading the custom header.
I have a controller in gateway microservice that accepts the MultipartFile and resends to the service behind it
#PostMapping
public ResponseEntity upload(#ApiParam(name = "file", value = "File", required = true) MultipartFile file)
throws BaseException {
if (Objects.isNull(file)){
throw new CheckFieldException("file", MultipartFile.class);
}
if (megabyte * maxFileSize - file.getSize() < 0){
return ResponseEntity.accepted().body(new DocumentResponseDTO(false, "File size exceeds " + maxFileSize + "MB"));
}
DiscoveryConfig.CashTracking config = discoveryConfig.getCashTracking();
UriComponents uriStatementUpload = UriComponentsBuilder.newInstance().scheme(config.getScheme())
.host(config.getHost()).port(config.getPort()).path(config.getExcelNominalOperationsPath()).build(true);
try {
HttpEntity<byte[]> fileEntity = new HttpEntity(file.getBytes());
ResponseEntity<DocumentResponseDTO> entity = restTemplate.postForEntity(uriStatementUpload.toUri(), fileEntity, DocumentResponseDTO.class);
return entity;
} catch (HttpClientErrorException e) {
return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
} catch (IOException e) {
return ResponseEntity.status(500).body("IOException while getting bytes stream from file");
}
}
and in CashTracking service there is also file upload like that:
#PostMapping(value = "/upload")
public ResponseEntity uploadExcelNominalOperationsFile(#ApiParam(name = "file", value = "File", required = true) MultipartFile file) throws IOException {
try (InputStream is = file.getInputStream()) {
log.info("Processing incoming Excel file with nominal operations");
Workbook workbook = new XSSFWorkbook(is);
log.info("Processing workbook");
Sheet sheet = workbook.getSheetAt(0);
log.info("Processing the first sheet");
List<NominalOperationVO> nominalOperationVOs = new ArrayList<>();
List<String> fileHeaders = new ArrayList<>();
And when the file is actually uploaded to the gateway service, the service behind it starts processing the file upload, but the MultipartFile file is null. I have explicitly put it in the Entity I have sent to the service behind the gateway, the question, what I'm doing wrong if it is null? If I do upload to that microservice directly, it process the request correctly.
The main stuff I was missing was putting the Http headers per specific multipart form's parts. They should be identical to what has been sent to the gateway service.
public ResponseEntity upload(#ApiParam(name = "file", value = "Файл", required = true) MultipartFile file)
throws BaseException {
if (Objects.isNull(file)){
throw new CheckFieldException("file", MultipartFile.class);
}
if (megabyte * maxFileSize - file.getSize() < 0){
return ResponseEntity.accepted().body(new DocumentResponseDTO(false, "File size exceeds " + maxFileSize + "MB"));
}
DiscoveryConfig.CashTracking config = discoveryConfig.getCashTracking();
UriComponents uriStatementUpload = UriComponentsBuilder.newInstance().scheme(config.getScheme())
.host(config.getHost()).port(config.getPort()).path(config.getExcelNominalOperationsPath()).build(true);
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultipartBodyBuilder multipartBodyBuilder = new MultipartBodyBuilder();
//here is the really needed stuff with 2 headers
Resource resource = new ByteArrayResource(file.getBytes());
multipartBodyBuilder.part("file", resource)
.header("Content-Type",file.getContentType())
.header("Content-Disposition","form-data; name=\"file\"; filename=\""+file.getOriginalFilename()+"\"");
// multipart/form-data request body
MultiValueMap<String, HttpEntity<?>> body = multipartBodyBuilder.build();
HttpEntity<MultiValueMap<String, HttpEntity<?>>> requestEntity
= new HttpEntity<>(body, headers);
ResponseEntity<DocumentResponseDTO> entity = restTemplate.postForEntity(uriStatementUpload.toUri(), requestEntity, DocumentResponseDTO.class);
return entity;
} catch (HttpClientErrorException e) {
return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
} catch (IOException e) {
return ResponseEntity.status(500).body("IOException while getting bytes stream from file");
}
}
I see almost all webservice for android are written in PHP code. With Java I found an example of a rest service to upload image. I coded follow that code but when run test on my android device and Advanced RESTClient of chorme, I get error: HTTP Status 500 - Internal Server Error: Servlet.init () for servlet [Jersey REST Service] threw exception.. My URL: "http://srv.triaxvn.com:8080/logisticwsm/file/image-upload"
In android I use code:
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
File sourceFile = new File(filePath);
String fileName = sourceFile.getName();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(FILE_UPLOAD_URL);
MultipartEntity entity = new MultipartEntity();
// Extra parameters if you want to pass to server
entity.addPart("fileDescription", new StringBody(""));
entity.addPart("fileName", new StringBody(fileName != null ? fileName : sourceFile.getName()));
// Adding file data to http body
FileBody fileBody = new FileBody(sourceFile, "application/octect-stream") ;
entity.addPart("attachment", fileBody);
//totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
My Restful web service code:
#Path("/file")
public class UploadFile {
private final String UPLOADED_FILE_PATH = "c:\\uploaded";
#POST
#Path("/image-upload")
#Consumes("multipart/form-data")
public Response uploadFile(MultipartFormDataInput input) throws IOException
{
//Get API input data
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
//Get file name
String fileName = uploadForm.get("fileName").get(0).getBodyAsString();
//Get file data to save
List<InputPart> inputParts = uploadForm.get("attachment");
for (InputPart inputPart : inputParts)
{
try
{
//Use this header for extra processing if required
#SuppressWarnings("unused")
MultivaluedMap<String, String> header = inputPart.getHeaders();
// convert the uploaded file to inputstream
InputStream inputStream = inputPart.getBody(InputStream.class, null);
byte[] bytes = IOUtils.toByteArray(inputStream);
// constructs upload file path
fileName = UPLOADED_FILE_PATH + fileName;
writeFile(bytes, fileName);
System.out.println("Success !!!!!");
}
catch (Exception e)
{
e.printStackTrace();
return Response.status(200).entity("Uploaded file name : "+e.getMessage()).build();
}
}
return Response.status(200)
.entity("Uploaded file name : "+ fileName).build();
}
//Utility method
private void writeFile(byte[] content, String filename) throws IOException
{
File file = new File(filename);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fop = new FileOutputStream(file);
fop.write(content);
fop.flush();
fop.close();
}
I do not know the error caused from by android code or Server Restful code and how to fix it
I need to simply upload a video from my Android Device to my Java Backend and after reading through some StackOverflow threads, I learnt that I need to POST my video as a Multipart request to the Java Backend.
I managed to implement the following, which basically POSTs the video file as a Multipart POST request.
Android Client:
private void uploadVideo(String videoPath) throws ParseException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("MY_SERVER_URL");
FileBody filebodyVideo = new FileBody(new File(videoPath));
StringBody title = new StringBody("Filename: " + videoPath);
StringBody description = new StringBody("This is a description of the video");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("video", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
httppost.setEntity(reqEntity);
// DEBUG
HttpResponse response = httpclient.execute( httppost );
HttpEntity resEntity = response.getEntity( );
// DEBUG
System.out.println( response.getStatusLine( ) );
if (resEntity != null) {
System.out.println( EntityUtils.toString(resEntity) );
} // end if
if (resEntity != null) {
resEntity.consumeContent( );
} // end if
httpclient.getConnectionManager( ).shutdown();
}
My question is, how do I receive the file from the Java Backend? Here's the Backend method that I need to modify. Can someone point out how I can receive the video file from the backend?
What I have right now:
#Path("/user")
public class UserAPI {
#POST
//To receive the file, What do I add below instead of the lines I've commented.
//#Produces(MediaType.APPLICATION_JSON)
//#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Path("/postvideo")
public VideoResponse PostVideo(){
//My code
}
}
Here is how I did it (without error handling, validation and stuff).
#POST
#Path("/")
#Consumes("multipart/form-data")
public Response uploadFileMultipart(MultipartFormDataInput input) {
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> inputParts = uploadForm.get("video");
String videoFileName = "GENERATE_YOUR_FILENAME_HERE.mp4";
File file = new File(filename);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fop = new FileOutputStream(file);
for (InputPart inputPart : inputParts) {
InputStream inputStream = inputPart.getBody(InputStream.class, null);
byte[] content = IOUtils.toByteArray(inputStream);
fop.write(content);
}
fop.flush();
fop.close();
return Response.status(HttpStatus.SC_OK).build();
}
guys. Need help with sending POST request with multipart-data.
I have a method to create request on my client side. Here it is:
public void sendMultipart(String cmd , Employee emp) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost(baseUrl + cmd);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
FileBody f = new FileBody(emp.getPhoto());
try {
StringBody s = new StringBody(emp.getLogin());
builder.addPart("name", s);
builder.addPart("file", f);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(RestTemplateRequester.class.getName()).log(Level.SEVERE, null, ex);
}
uploadFile.setHeader("Accept", "application/json");
uploadFile.setHeader("Content-type", "application/json");
uploadFile.setHeader("enctype","multipart/form-data");
uploadFile.setHeader("accept-charset","UTF-8");
//builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);
//builder.addBinaryBody(emp.getLogin(), emp.getPhoto(), ContentType.MULTIPART_FORM_DATA, "file");
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
try {
HttpResponse httpResponse = httpClient.execute(uploadFile);
int status = httpResponse.getStatusLine().getStatusCode();
String str = httpResponse.getStatusLine().getReasonPhrase();
} catch (IOException ex) {
Logger.getLogger(RestTemplateRequester.class.getName()).log(Level.SEVERE, null, ex);
}
}
Also I have a method to handle request on my server side:
#RequestMapping(value = "photo", consumes = "multipart/form-data")
public #ResponseBody
void uploadFileHandler(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Create the file on server
File serverFile = new File(name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
} catch (Exception e) {
e.getMessage();
}
}
}
And in my context:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<property name="maxUploadSize" value="100000" />
</bean>
The problem which I have now - is a 408 error "Request Time Out".
My common aim is - send JSON with file to server. I so green with web services in java, so i got some troubles.
Please, It will be great, if someone can give me a little advice. Thank you.
What you are trying to do is not an accepted way to upload file (Embedding file inside of JSON). And furthermore your Upload file handler is not suited to handle JSON instead in can handle only a multipart file and a name as parameter. Please look at my previous q/a on how to successfully upload a file using Spring MVC Multipart and RestTemplate.