0% found this document useful (0 votes)
22 views1 page

Download

The document describes a Java servlet class that allows downloading of files. The servlet gets the file name from a request parameter, sets the response content type and headers for file download, then writes the file contents to the response.

Uploaded by

Baranishankar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views1 page

Download

The document describes a Java servlet class that allows downloading of files. The servlet gets the file name from a request parameter, sets the response content type and headers for file download, then writes the file contents to the response.

Uploaded by

Baranishankar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

/*

* To change this license header, choose License Headers in Project Properties.


* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.codejava.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author ELCOT
*/
@WebServlet("/downloadservlet")
public class downloadservlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
String name=request.getParameter("filename");
String
path=getServletContext().getRealPath("/"+"files"+File.separator+name);
File f=new File(path);
if(f.exists())
{
response.setContentType("application/octet-stream");
response.setContentLength((int)f.length());
String key="Content-Disposition";
String hvalue=String.format("attachment;filename=\"%s\"",f.getName());
response.setHeader(key,hvalue);
FileInputStream in=new FileInputStream(f);
int i;
while((i=in.read())!=-1)
{
out.write(i);
}
in.close();
out.close();
}else{
out.println("file not available");
}
}
}

You might also like