PDA

View Full Version : returning binary data from http request



khanmurtuza
Apr 9th, 2008, 03:46 PM
I want to return binary data for an http get request, what I did is return the bytearray as string.

Problem is client can't decode it as the return content type is text/html.

can anyone tell me how to return binary data for an http request.

smrutimo
Apr 9th, 2008, 03:58 PM
1. Try setting the content type of the response to whatever u are trying to send.
2. Get the handle on the SerlvletOutputStream from the response and stream your bytes to that.

carlescs
Apr 10th, 2008, 12:58 AM
What I did was to make a simple "binary view".


package cat.company.projecte.vistes;

import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.web.servlet.view.AbstractView;

import cat.company.projecte.model.Fitxer;

public class VistaFitxerBinari extends AbstractView {

@Override
protected void renderMergedOutputModel(Map model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Fitxer fitxer=(Fitxer) model.get("fitxer");
response.setContentType(fitxer.getTipusMime());
response.setHeader("Content-Disposition","attachment; filename=\"" + fitxer.getNom() +"\"");
OutputStream out=response.getOutputStream();
IOUtils.copy(fitxer.getContingut(), out);
out.flush();
out.close();
}

}


Where "Fitxer" is a bean containing:



public class Fitxer {
private Integer id;
private String nom;
private String tipusMime;
private String localitzacio;
private Boolean buit;

private Document document;

private InputStream contingut;

... getters and setters...


I think you can modify this to meet your needs. I'm not sure if this is the best approach to this problem...