Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, need help in solving an issue in code while uploading a file using webclient in Java as i keep getting errors. The code I tried:


The code I tried returns error 'end of file never reached'. I have tried several solutions like converting to byte etc but nothing worked. Is there something missing or need to be removed from this code extract to make it working. Thanks.

What I have tried:

<pre lang="Java">var file = new File(tempDirectory + File.separator + myFile);

   var multipartBodyBuilder = new MultipartBodyBuilder();
   multipartBodyBuilder.part("ticket", ticket, MediaType.TEXT_PLAIN);
   multipartBodyBuilder.part("file", new FileSystemResource(filePath), MediaType.APPLICATION_PDF).filename(fileName);
   
   var mimeMultipartData = multipartBodyBuilder.build();
HttpHeaders headers = new HttpHeaders();
   	headers.setContentType(MediaType.MULTIPART_FORM_DATA);
WebClient webclient = client.getConnectionProvider().createWebClientBuilder(url, true, headers)
   			.build();
   return webclient.post().body(BodyInserters.fromMultipartData(builder.build())).exchangeToMono(response -> {
   		if (response.statusCode().isError()) {
   			return response.createException().flatMap(Mono::error);
   		}
   		return response.bodyToMono(String.class);
   	}).block().trim();

}
Posted
Comments
Dave Kreskowiak 19-Feb-24 11:58am    
I keep getting errors...
And you failed to post the exact error messages. Kind of important to know what those are to diagnose the problem.
developer new 2024 20-Feb-24 2:47am    
The error is always 'end of file never reached'

1 solution

Looks like the file path might be wrong, or the resource handling needs work. Also, ditch .block() and handle things asynchronously. Double-check the file path and make sure it points to the actual file. Verify your resource and check server logs for errors or configuration problems.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900