Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get headers of MultipartFile?

Using spring MVC I receive multipart files in the controller this way

@RestController
public class FilesController {

@PostMapping(path = ("/files"), consumes = {"multipart/form-data", "multipart/mixed"})
public Reference createFile(
        @RequestPart(value = "description") FileDescription fileDesc,
        @RequestPart(value = "attachments", required = false) List<MultipartFile> attachments) {

Some parts of the multipart request may contain headers like "Content-ID", "Content-Location" and so on. But spring interface MultipartFile doesn't provide a method to get any header I want, only getContentType as I see. How I can get all provided headers?

Important point is that in request I could have multipart/mixed as a part of multipart/form-data. So every part of the message has its own map of headers. If I use @RequestHeader, I can see main headers of the request, but there are no headers of a specific part of multipart.

like image 823
Ilya Avatar asked Jan 25 '26 04:01

Ilya


2 Answers

There might be another way, but the one I know of is to ask for a MultipartHttpServletRequest in your method signature.

@PostMapping(path = ("/files"), consumes = {"multipart/form-data", "multipart/mixed"})
public Reference createFile(MultipartHttpServletRequest multipartRequest)

You can ask for other arguments if need be.

This object allows you to access details of the multipart in a finer-grained way. For example, you can access each part's header using getMultipartHeaders(String paramOrFileName). You also have methods to access the files content this way, so you would not typically need to keep you @RequestPart inside the method signature.

like image 167
GPI Avatar answered Jan 27 '26 16:01

GPI


We can also use javax.servlet.http.Part instead of MultipartFile. Interface Part has getHeader method.

@RequestPart(value = "attachments", required = false) List<Part> attachments
like image 24
Ilya Avatar answered Jan 27 '26 18:01

Ilya