JSP file download

<a href="DownloadServlet?fileName=殷志源03.jpg"> download pictures </a>

package org.student.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

/**
 * Servlet implementation class DownloadServlet
 */
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected voidthe doGet (the HttpServletRequest Request, the HttpServletResponse Response) throws ServletException, IOException {
         // . 1 disposed coding 
        Request.setCharacterEncoding ( "UTF-. 8" );
         // 2 acquires the downloaded file name 
        String fileName = request.getParameter ( "fileName" );    
         // 3 download files you need to set the message header, can not solve the current download Chinese name garbled 
        the Response.Addheader ( "Content-type", "the Application / OCTET-Stream"); // MIME type: binary files (any file) 
        the Response.Addheader ( ; "Content-Disposition", "the attachement; filename =" + fileName) // named abc.txt: fileName contains the file extension
         // absolute path of the file 4
        String realPath = "D:\\studyJspForUpload\\newUpload";
        //5.创建文件对象 
        File file = new File(realPath,fileName);
        if(!file.exists()){
            response.getWriter().write("文件不存在");
            return;
        }
        IOUtils.copy(new FileInputStream(file), response.getOutputStream());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

 

Guess you like

Origin www.cnblogs.com/ejwbytshooting/p/12590047.html