Java spring resttemplate multipartfile

Spring — RestTemplate File Upload Example

Following example shows how to upload a file by using RestTemplate .

Example

A Spring Restful Controller to handle file upload

@RestController @RequestMapping("/upload") public class FileUploadController < @RequestMapping(method = RequestMethod.POST) public String handleFileUpload( @RequestParam("user-file") MultipartFile multipartFile) throws IOException < String name = multipartFile.getOriginalFilename(); System.out.println("File name: "+name); //todo save to a file via multipartFile.getInputStream() byte[] bytes = multipartFile.getBytes(); System.out.println("File uploaded content:\n" + new String(bytes)); return "file uploaded"; >>

To try examples, run embedded tomcat (configured in pom.xml of example project below):

RestTemplate uploading a File

public class UploadClient < public static void main(String[] args) throws IOException < MultiValueMapbodyMap = new LinkedMultiValueMap<>(); bodyMap.add("user-file", getUserFileResource()); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity requestEntity = new HttpEntity<>(bodyMap, headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity response = restTemplate.exchange("http://localhost:8080/upload", HttpMethod.POST, requestEntity, String.class); System.out.println("response status: " + response.getStatusCode()); System.out.println("response body: " + response.getBody()); > public static Resource getUserFileResource() throws IOException < //todo replace tempFile with a real file Path tempFile = Files.createTempFile("upload-test-file", ".txt"); Files.write(tempFile, "some test content. \nline1\nline2".getBytes()); System.out.println("uploading: " + tempFile); File file = tempFile.toFile(); //to upload in-memory bytes use ByteArrayResource instead return new FileSystemResource(file); >>
uploading: C:\Users\Joe\AppData\Local\Temp\upload-test-file1051379468467597241.txt
response status: 200
response body: file uploaded
File name: upload-test-file4223155062528304169.txt File uploaded content: some test content. line1 line2

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 5.0.2.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.0.1 Java Servlet API
  • commons-fileupload 1.3.2: The Apache Commons FileUpload component provides a simple yet flexible means of adding support for multipart file upload functionality to servlets and web applications.
  • JDK 1.8
  • Maven 3.3.9

Источник

How to call MultipartFile Spring REST URL with RestTemplate

Spring REST URL: Test method: Exception: Invalid amount of variables values in [http://test.com:8080/DMW-skeleton-1.0/media/uploadMultipartFile////]: expected 4; got 0 Solution: Question: When I try to call following MultipartFile Spring REST url with my Spring Template base Test method, I got following exception.

How to call MultipartFile Spring REST URL with RestTemplate

When I try to call following MultipartFile Spring REST url with my Spring Template base Test method, I got following exception. How can I make this correct. Thanks.

Spring REST URL:

 @RequestMapping(value = "/media/uploadMultipartFile////", method = RequestMethod.POST) public @ResponseBody MediaHttp uploadMultipartFile(@RequestParam MultipartFile file, @PathVariable String token, @PathVariable String title, @PathVariable String trailId, @PathVariable String wpId, HttpServletResponse response) 

Test method:

try < // Message Converters List> messageConverters = new ArrayList>(); messageConverters.add(new FormHttpMessageConverter()); messageConverters.add(new SourceHttpMessageConverter()); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(new MappingJacksonHttpMessageConverter()); // RestTemplate RestTemplate template = new RestTemplate(); template.setMessageConverters(messageConverters); // URL Parameters MultiValueMap parts = new LinkedMultiValueMap(); parts.add("token", "nkc2jvbrbc"); parts.add("title", "test mp4 file"); parts.add("trailId", "2"); parts.add("wpId", "7"); parts.add("file", new FileSystemResource("C:\\Users\\Public\\Pictures\\Sample Pictures\\test.mp4")); // Post MediaHttp result = template.postForObject(Constants.APPLICATION_URL + "/media/uploadMultipartFile////", parts, MediaHttp.class); > catch (Exception e)

Invalid amount of variables values in [http://test.com:8080/DMW-skeleton-1.0/media/uploadMultipartFile////]: expected 4; got 0

The message is pretty clear, you don’t specify any path parameters for submission. You only provide a map which will be send as the body of the request.

change your call to include those parameters as the last part of the method call.

// URL Parameters MultiValueMap parts = new LinkedMultiValueMap(); parts.add("file", new FileSystemResource("C:\\Users\\Public\\Pictures\\Sample Pictures\\test.mp4")); // Post MediaHttp result = template.postForObject(Constants.APPLICATION_URL + "/media/uploadMultipartFile////", parts, MediaHttp.class, "nkc2jvbrbc", "test mp4 file", "2", "7); 

Sending Multipart File as POST parameters with, I am working with Spring 3 and RestTemplate. I have basically, two applications and one of them have to post values to the other app. through rest template. When the values to post are Strings, it’s work perfect, but when i have to post mixed and complex params (like MultipartFiles) i get an converter exception. As example, i …

Sending a MultipartFile as a Request Param to REST server using Angular2

I need to upload a photo to the server which has been written using Spring Boot. For the front end which sends the request I use Angular2.

This is my API which accepts the HTTP request. It works fine. (I tested it using Postman)

@RequestMapping(method = RequestMethod.POST, value = "/tender/save-new/save-photo") public ResponseEntity uploadPhoto(@RequestParam("file") MultipartFile file)< if (file.isEmpty()) < ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setMessage("DEBUG: Attached file is empty"); return new ResponseEntity(errorResponse, HttpStatus.NOT_FOUND); > String returnPath = null; try < // upload stuff >catch (IOException e) < ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setMessage(e.getMessage()); return new ResponseEntity(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR); > return new ResponseEntity(returnPath, HttpStatus.OK); > 

I am not sure how should I write the code in Angular2 to call the server. Following is what I have come up with.

 savePhoto(photoToSave: File) < let formData: FormData = new FormData(); formData.append('file', photoToSave); let savedPath = this._http .post(this._endpointUrl + "tender/save-new/save-photo", formData) .map( res => < return res.json(); >) .catch(handleError); return savedPath; > 

As you can see, I append the ‘file’ parameter to the form data before sending it. Server method accepts the RequestParam as ‘file’ .

But, in the server log, I get following error.

org.springframework.web.multipart.MultipartException: Current request is not a multipart request at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:190)

Note that I haven’t declared a CommonsMultipartResolver bean since SprinBoot implicitly handles it. (I have heard this. Please correct if I am wrong.)

I think that the error comes up because of a missing value in the request. What Spring is saying by handleMissingValue ? What am I missing?

you need to specify that your controller is expecting multipart

@RequestMapping(method = RequestMethod.POST, value = "/tender/save-new/save-photo", consumes = ) public ResponseEntity uploadPhoto(@RequestParam("file") MultipartFile file) 

Also to solve the CORS problem you need to add the methods you are planning to use in your cors mapping, try something like this

 @Configuration public class WebMvcConfiguration < @Bean public WebMvcConfigurer corsConfigurer() < return new WebMvcConfigurerAdapter() < @Override public void addCorsMappings(CorsRegistry registry) < registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD"); >>; > > 

i had the same problem, this is the solution i am using right now:

for the back end using spring boot:

 @RequestMapping(value="/save", method = RequestMethod.POST) public ResponseEntity saveTemp(@RequestParam("file") MultipartFile file) throws Exception < String nomFichier=file.getOriginalFilename(); try < byte[] bytes = file.getBytes(); File fi=new File(tempRepo+nomFichier); fi.getParentFile().mkdirs(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream((new FileOutputStream(fi))); bufferedOutputStream.write(bytes); bufferedOutputStream.close(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); > return new ResponseEntity<>(HttpStatus.OK); > 

for the front end using Angular2:

Spring MVC: java.util.Optional MultipartFile, Spring 4.1 introduced support for java.util.Optional in @RequestParam and @RequestHeader in controller method parameters. I am using Spring 4.3.10. If an Optional @RequestParam is not present in the request parameters, that value should be Optional.EMPTY as opposed to null.However, …

Spring Resttemplate : how to post file and common String data at the same time

I meet a request to upload files with spring resttemplate to upload files with http header "multipart/form-data", also some other normal parameters need to be posted. how to implements that?

you can use the following code in your application to have both multipartfile and normal request parameters at the same time.

  • Replace the url with your own.
  • replace param and value according to your normal parameters. String url ="http://example.com"; String fileAbsPath ="absolute path of your file"; String fileName = new File(fileAbsPath).getName(); Files.readAllBytes(Paths.get(fileAbsPath)); MultiValueMap data = new LinkedMultiValueMap(); ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(Paths.get(fileAbsPath))) < @Override public String getFilename() < return fileName; >>; data.add("file", resource); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("file","application/pdf"); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url) .queryParam("param1", "value1") .queryParam("param2", "value2") HttpEntity<> entity = new HttpEntity<> (data, requestHeaders); RestTemplate restTemplate = new RestTemplate(); ResponseEntity result =restTemplate.exchange( builder.toUriString(), HttpMethod.POST, entity, String.class); System.out.println(result.getBody());
 HttpHeaders headers = getCASHeaders(MediaType.MULTIPART_FORM_DATA); LinkedMultiValueMap params = new LinkedMultiValueMap<>(); params.add("fileField", new FileSystemResource(""));//get file resource params.add("stringfield", stringPayload); HttpEntity requestEntity = new HttpEntity<>(params, headers); ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class); 

This will send post call with two param, you can add more according to your wish.

Please have a look at this stackoverflow answer as well

I got the error "cannot be cast to java.lang.String" although my code does not have any casting.

Spring boot - Post a from with a MultipartFile using, Get list of JSON objects with Spring RestTemplate. 218. How to POST form data with Spring RestTemplate? 6. MultipartFile + String as Request Param using RestTemplate in Spring. Hot Network Questions Short story about a man accompanied by a woman who tries to walk out of an endless city only to end up …

Источник

spring-rest-template-multipart-upload

This quick tutorial focuses on how to upload a multipart file using Spring’s RestTemplate.

We’ll see both a single file and multiple files – upload using the RestTemplate.

2. What is an HTTP Multipart Request?

Simply put, a basic HTTP POST request body holds form data in name/value pairs.

On the other hand, HTTP clients can construct HTTP multipart requests to send text or binary files to the server; it’s mainly used for uploading files.

Another common use-case is sending the email with an attachment. Multipart file requests break a large file into smaller chunks and use boundary markers to indicate the start and end of the block.

Explore more about multipart requests here.

3. Maven Dependency

This single dependency is enough for the client application:

 org.springframework spring-web 5.0.7.RELEASE 

4. The File Upload Server

The file server API exposes two REST endpoints for uploading single and multiple files respectively:

5. Uploading a Single File

First, let’s see single file upload using the RestTemplate.

We need to create HttpEntitywith header and body. Set the content-type header value to MediaType.MULTIPART_FORM_DATA. When this header is set, RestTemplate automatically marshals the file data along with some metadata.

Metadata includes file name, file size, and file content type (for example text/plain):

HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA);

Next, build the request body as an instance of LinkedMultiValueMap class. LinkedMultiValueMap wraps LinkedHashMap storing multiple values for each key in a LinkedList.

In our example, the getTestFile( ) method generates a dummy file on the fly and returns a FileSystemResource:

MultiValueMap body = new LinkedMultiValueMap<>(); body.add("file", getTestFile());

Finally, construct an HttpEntity instance that wraps the header and the body object and post it using a RestTemplate.

Note that the single file upload points to the /fileserver/singlefileupload/ endpoint.

In the end, the call restTemplate.postForEntity( ) completes the job of connecting to the given URL and sending the file to the server:

HttpEntity> requestEntity = new HttpEntity<>(body, headers); String serverUrl = "http://localhost:8082/spring-rest/fileserver/singlefileupload/"; RestTemplate restTemplate = new RestTemplate(); ResponseEntity response = restTemplate .postForEntity(serverUrl, requestEntity, String.class);

6. Uploading Multiple Files

In multiple file upload, the only change from single file upload is in constructing the body of the request.

Let’s create multiple files and add them with the same key in MultiValueMap.

Obviously, the request URL should refer to endpoint for multiple file upload:

MultiValueMap body = new LinkedMultiValueMap<>(); body.add("files", getTestFile()); body.add("files", getTestFile()); body.add("files", getTestFile()); HttpEntity requestEntity = new HttpEntity<>(body, headers); String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/"; RestTemplate restTemplate = new RestTemplate(); ResponseEntity response = restTemplate .postForEntity(serverUrl, requestEntity, String.class);

It’s always possible to model single file upload using the multiple file upload.

7. Conclusion

In conclusion, we saw a case of MultipartFile transfer using Spring RestTemplate.

As always, the example client and server source code is available over on GitHub.

Источник

Читайте также:  Bitrix закомментировать код php
Оцените статью