Reputation: 690
I have a Jersey service which returns a zip file as a response. I call this service using cURL. I am getting a file response, but the zip file is unreadable. I noticed that the original file is around 20MB but the size of the file I got is only 3.2KB
I am trying the following code:
Jersey:
@GET
@Path("/get-zip")
@Produces("application/zip")
@Consumes(MediaType.APPLICATION_JSON)
public Response getZip() throws IOException{
File fileObj = new File('myfile.zip');
return Response.ok((Object)fileObj)
.header("Content-Disposition", "attachment; filename=\"" + fileObj.getName() + "\"")
.build();
}
cURL Code:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
$file = curl_exec($curl);
$file_array = explode("\n\r", $file, 2);
$header_array = explode("\n", $file_array[0]);
foreach($header_array as $header_value) {
$header_pieces = explode(':', $header_value);
if(count($header_pieces) == 2) {
$headers[$header_pieces[0]] = trim($header_pieces[1]);
}
}
header('Content-type: ' . $headers['Content-Type']);
header('Content-Disposition: ' . $headers['Content-Disposition']);
echo $file_array[1];
Anything I am missing?
Upvotes: 0
Views: 559
Reputation: 2289
MediaStreamer streamer = new MediaStreamer(fileObj.getInputStream());
return Response.ok()
.header(HttpHeaders.CONTENT_LENGTH, fileObj.getContentLength())
.header(HttpHeaders.CONTENT_DISPOSITION, fileObj.getContentDisposition())
.entity(streamer)
.type(fileObj.getContentType())
.build();
and MediaStreamer
look like this
import com.google.common.io.ByteStreams;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;
import java.io.*;
public class MediaStreamer implements StreamingOutput {
private InputStream is;
public MediaStreamer(InputStream is) {
this.is = is;
}
@Override
public void write(OutputStream os) throws IOException, WebApplicationException {
Writer writer = new BufferedWriter(new OutputStreamWriter(os));
ByteStreams.copy(is, os);
writer.flush();
}
}
Upvotes: 1