Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java servlet read a file and send it as response

Tags:

jakarta-ee

I'm trying to write a servlet which will read (download) file from a remote location and simply send it as response, acting more-or-less like a proxy to hide the actual file from getting downloaded. I'm from a PHP background where I can do it as simply as calling file_get_contents.

Any handy way to achieve this goal using servlet/jsp?

Thanks

like image 792
Shafiul Avatar asked Dec 03 '13 03:12

Shafiul


People also ask

How do I write a response to a servlet?

response. setHeader( "Content-Disposition" , "attachment; filename=\"" + pdfName + "\"" ); Once the servlet accesses the file, now we need to read the contents of the file using FileInputStream. So, get the object of the FileInputStream and loop through the document to read and write to the PrintWriter object.

How can we upload the file to the server using servlet?

Code a Java Servlet to handle the file upload process; Annotate the file upload Servlet with the @MultipartConfig annotation; In the Servlet, save the uploaded file to the server's file system; and. Send a response back to the browser to indicate that the file successfully uploaded.

Which method is used to send response of one servlet into another?

SendRedirect in servlet The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file.

What is Httpservlet response?

All Known Implementing Classes: HttpServletResponseWrapper public abstract interface HttpServletResponse extends ServletResponse. Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies.


1 Answers

int BUFF_SIZE = 1024;
byte[] buffer = new byte[BUFF_SIZE];
File fileMp3 = new File("C:\Users\Ajay\*.mp3");
FileInputStream fis = new FileInputStream(fileMp3);
response.setContentType("audio/mpeg");
response.setHeader("Content-Disposition", "filename=\"hoge.txt\"");
response.setContentLength((int) fileMp3.length());
OutputStream os = response.getOutputStream();

try {
    int byteRead = 0;
    while ((byteRead = fis.read()) != -1) {
       os.write(buffer, 0, byteRead);

    }
    os.flush();
} catch (Exception excp) {
    downloadComplete = "-1";
    excp.printStackTrace();
} finally {
    os.close();
    fis.close();
}
like image 125
Ajay Takur Avatar answered Oct 22 '22 22:10

Ajay Takur