How would you Http-Post a MultipartFile?

705 Views Asked by At

I am trying to build a file-uploader with Java/Spring-boot/Vaadin.

https://vaadin.com/components/vaadin-upload/java-examples

That Uploader gives me a MemoryBuffer. How can I post this to my backend, which looks like this:


@RestController
@RequestMapping("files")
public class FilesController {
...
    @PostMapping
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
        try {
            fileService.save(file);
            return ResponseEntity.status(HttpStatus.OK)
                    .body(String.format("File uploaded successfully: %s", file.getOriginalFilename()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(String.format("Could not upload the file: %s!", file.getOriginalFilename()));
        }
    }
...

I tried something like:

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost("http://localhost:9091/upload/files");

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();

but I don't know how to add the requested MultipartFiles. Thank you :)

1

There are 1 best solutions below

0
On

I haven't tested this code, so it may or may not work. It's based on a Baeldung article and the FileData JavaDoc.

FileData fileData = memoryBuffer.getFileData();

MultipartEntityBuilder builder = MultipartEntityBuilder.create();         
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("blabla", fileData.getFile(), 
    ContentType.create(fileData.getMimeType()), 
    fileData.getFileName());
HttpEntity entity = builder.build();
httppost.setEntity(entity);