Vance Cagle
Vance Cagle

Reputation: 123

Server code for handling a file upload made by HttpClient

I have a Java HttpClient that executes the following code:

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://exampleutl.com/upload/");

File file = new File("C:/src_path/binary.doc");

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

builder.setMode(HttpMultipartMode.STRICT);

FileBody fileBody = new FileBody(file); //image should be a String
builder.addPart("file", fileBody);
post.setEntity(builder.build());

client.execute(post);

I cannot figure out what the server method mapped to the /upload/ path should look like.

The server that accepts this file upload request is Spring 4.0. Something like this:

@RequestMapping(method = RequestMethod.POST, value = "/upload/")
public @ResponseBody String saveUpload(UploadDto dto) throws IOException,ServletException {
    File file = new File("C:/dest_path/" + dto.getFile().getOriginalFilename());
    FileUtils.writeByteArrayToFile(file, dto.getFile().getBytes());
    return "success";
}

The above server method gets called by the client.execute() but the UploadDto is empty. Here is the UploadDto:

public class UploadDto {
    private MultipartFile file;

    public MultipartFile getFile() {
        return file;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }
}

Any assistance would be greatly appreciated!

Upvotes: 0

Views: 287

Answers (2)

Vance Cagle
Vance Cagle

Reputation: 123

The ultimate answer was that the server method should look like this:

@RequestMapping(method = RequestMethod.POST, value = "/upload/")
public @ResponseBody String saveUpload(@RequestParam("file") final MultipartFile mpf) throws IOException, ServletException, FileUploadException {
    File file = new File("C:/dest_path/" + mpf.getOriginalFilename());
    FileUtils.writeByteArrayToFile(file, mpf.getBytes());

    return "success";
}

As mentioned by Sotirios Delimanois the MultipartResolver is indeed a required part of the solution as well:

@Bean
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    return multipartResolver;
} 

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279890

You seem to be missing a MultipartResolver bean from your Spring servlet context. Something like

@Bean
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    return multipartResolver;
}

You're sending your request to

HttpPost post = new HttpPost("http://exampleutl.com/upload/");

Assuming your context path is ROOT, ie. empty, your handler method should be mapped to /upload.

@RequestMapping(method = RequestMethod.POST, value = "/upload")

Upvotes: 1

Related Questions