Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring : get response as Multipart File from REST WebService

I am creating POC for RESTFUL Web service using Spring 4.0. Requirement is to receive MultipartFile as Response from REST WEB-Service.

REST Service Controller

@RequestMapping(value="/getcontent/file", method=RequestMapping.post)
public MultipartFile getMultipartAsFileAsObject() {

    File file = new File("src/test/resources/input.docx");
    FileInputStream input = new FileInputStream(file);
    MultipartFile multipartFile = new MockMultipartFile("file",file.getName(),
                                 "application/docx", IOUtils.toByteArray(input));

    return multipartFile        
}

I call this service using third party Clients and Apache Http Client as well. kindly have a look on output.

Using Third party REST client ie. Postman

output looks like Json -

{
    "name" : "file",
    "originalfilename" : "sample.docx",
    "contentType" : "application/docx",
    "content" : [
                82,
                101,
                97,
                100,
                101,    
                32,
                32,
                .
                .
                .
                .
                .
            ]  
}

Apache HTTP Client Sample code

private static void executeClient() {
HttpClient client = new DefaultHttpClient();
HttpPost postReqeust = new HttpPost(SERVER_URI);

try{
    // Set Various Attributes

    HttpResponse response = client.execute(postReqeust) ;

    //Verify response if any
    if (response != null)
    {
        InputStream inputStream = response.getEntity().getContent();
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);

        OutputStream outputStream = new FileOutputStream
                                   (new File("src/main/resource/sample.docx"));
        outputStream.write(buffer);
        outputStream.flush();
        outputStream.close();
    }

}
catch(Exception ex){
    ex.printStackTrace();
}

Output of Apache Http client

file is getting Created but It is empty. (0 bytes).

like image 331
Morez Avatar asked Jan 27 '16 06:01

Morez


People also ask

Can we use multipart and @requestbody together in spring?

You can use @RequestPart like below. This will support both json object and multipart file. In order to test it using curl you can create one file for your json part (reportData).

How does MultipartFile work in spring?

The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for copying file contents to a session-level or persistent store as and if desired. The temporary storages will be cleared at the end of request processing.


1 Answers

 I found some interesting answers from multiple stackoverflow questions. 
 Links are given below

file downloading in restful web services

what's the correct way to send a file from REST web service to client?

For Sending single file : (copied from above sources)

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile() {
  File file = ... // Initialize this to the File path you want to serve.
  return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
      .header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ) //optional
      .build();
}

For Sending Zip file : (copied from above sources)

1) Approach First :

You can use above method to send any file / Zip.

private static final String FILE_PATH = "d:\\Test2.zip";
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile() {
    File file = new File(FILE_PATH);
    ResponseBuilder response = Response.ok((Object) file);
    response.header("Content-Disposition", "attachment; filename=newfile.zip");
    return response.build();

}

2) Approach Second :

@GET
@Path("/get") 
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public StreamingOutput helloWorldZip() throws Exception {
    return new StreamingOutput(){
    @Override
        public void write(OutputStream arg0) throws IOException, WebApplicationException {
            // TODO Auto-generated method stub
            BufferedOutputStream bus = new BufferedOutputStream(arg0);
            try {
                Thread.currentThread().getContextClassLoader().getResource("");
                File file = new File("d:\\Test1.zip");
                FileInputStream fizip = new FileInputStream(file);
                byte[] buffer2 = IOUtils.toByteArray(fizip);
                bus.write(buffer2);
            } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
        }
    };
}
like image 64
Morez Avatar answered Oct 13 '22 18:10

Morez