Link to home
Start Free TrialLog in
Avatar of GregL
GregL

asked on

Set filename for binary data in HttpServletResponse

I have a servlet that retrieves binary data files from a database.  I can send the file to the client with no problems.  I use req.getOutputStream().  How do I set the initial filename that the user sees in the Save As dialog?
Avatar of diakov
diakov

Won't this help?
//
saveFileDialog1 = new java.awt.FileDialog(this);
saveFileDialog1.setMode(FileDialog.SAVE);
saveFileDialog1.setTitle("Save");
saveFileDialog1.setFile("initial.file");
Avatar of GregL

ASKER

Sorry diakov,  I am looking for a way for the servlet to set the filename the client sees.  There is no client-side java..

Thanks,

GregL
So you generate the HTML dynamically. Isn't there a field in the HTML response header that says this?

Cheers,
  Nik.
Avatar of GregL

ASKER

I have tried
res.setContentType( contentType + "; filename=" + fileName );

and

res.setHeader( "filename" , fileName );

Neither works..
Your file will be accessed through an URL.
If you write
<a href="myServlet/toto.hqx">download the file</a>
your user will be asked to save the file "toto.hqx".


Avatar of GregL

ASKER

Sorry segurets.. I am sending the data back to client in response to a form POST.  Your answer assumes I am using a GET.  This is not a simple link to a file, it is a database transaction that packages the data and sends it back to the client.  I must return the data using a binary stream.

Thanks,

GregL
Hi again,

try setContentType("application/filename.ext") with some mime type specifications like.

Cheers,
  Nik.
Avatar of GregL

ASKER

I tried diakov's suggestion.  No luck..  Here is a snippet of my code that may help..
Hashtable h = (Hashtable)o;
String contentType = (String)h.get( "mime_type" );
String fileName = (String)h.get( "file_name" );
byte [] content = (byte [])h.get( "content" );
if( (contentType != null) && (fileName != null) && (content != null) )
{
    res.setContentType( contentType );
    res.setContentLength( content.length );
    res.setHeader( "pragma", "no-cache" );
    OutputStream out = res.getOutputStream();
    out.write( content, 0, content.length );
    out.close();
}
else
{
    res.setContentType( "text/html" );
    PrintWriter out = res.getWriter();
    out.print( "The hashtable was not valid!" );
    out.close();
}

seguret's answer is basicly right.  Try

<form action="myServlet/toto.hqx" method=post>

Avatar of GregL

ASKER

Sorry, I found the real answer..

res.setHeader( "Content-Disposition","attachment; filename=" + fileName + ";" );

Thanks, for the help..

Greg L.
ASKER CERTIFIED SOLUTION
Avatar of linda101698
linda101698

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial