Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Outputting byte array of file to a download file output prompt

807603Dec 14 2007 — edited Dec 27 2007
Afternoon chaps.

I was wondering if any of you guys have ever successfully got a byte array of a file and outputted it in such a way to display a download prompt, like do you want to run or save as.

The scenario is a server transfers a byte array of a file across to the client, and the client simply prompt whether the user wants to run the file or save the file to disk.

I have seen several solutions to this which do this by already having the file on the same system, but none of these solutions relate across to my idea.

I know this must be possible but I cant work out what to use or how to do it. I have got some code to the point of creating a prompt, but the file it recieves is corrupt, well.. is the right format for the file extension.

I'll post the code below and you guys can let me know your ideas of your known solutions.

Again, the idea is simply to output a byte array received from the server to a file download run or save as prompt.

The way the code currently works is a html form passes a request for 'fileName' to the fileDownload class. Oh, and the server is running on rmi.

All i simply need is how to output the byte array properly to a) produce a prompt for run/save, and b) output a valid file.

Thanks.
import java.io.*;
import java.rmi.*;
import java.util.*;
import java.lang.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class filedownload extends HttpServlet
{

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		PrintWriter html = response.getWriter();

		String filename = "";
		filename = request.getParameter("fileName");

      		try
		{
                        String name = "//localhost/serverName";
       			server fi = (server) Naming.lookup(name);
			byte[] filedata = fi.downloadFile(filename);
         		File file = new File(filename);
			FileOutputStream fos = new FileOutputStream(file);
			response.setContentType("image/jpeg"); 
        		response.setContentLength(filedata.length);
        		response.setHeader("Content-Disposition","attachment; filename="+file.getName());
			fos.write(filedata,0,filedata.length);
			fos.flush();
			fos.close();
                }
		catch(Exception e)
		{
        		System.err.println("PoUnDFiSH exception: "+ e.getMessage());
        		e.printStackTrace();
      		}
   	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 24 2008
Added on Dec 14 2007
21 comments
4,116 views