jsp中的下載鏈接


1、下載鏈接jsp界面(a鏈接直接鏈文件可以看出文件在服務器中的路徑,用servlet處理的鏈接則看不出)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="日期My97DatePickerBeta.rar">下載</a>
<br/>
<a href="DownloadServlet?file=1.jpg">下載1</a>
<br/>
<a href="DownloadServlet?file=2.jpg">下載2</a>
</body>
</html>

備注:a鏈接直接鏈文件 遇到文件名為中文時會出現404錯誤,因為中文亂碼了,所以找不到文件,解決方案:

在tomcat中指定url編碼即可,找到tomcat目錄中的conf下的server.xml,然后打開,找到端口的配置的標簽位置:

 <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>

然后加上URIEncoding="UTF-8"這個配置,重新啟動tomcat即可(上面代碼我已加上)
摘:http://ykyfendou.iteye.com/blog/2094734

 

2、DownloadServlet處理代碼

package com.java.servlet;

import java.io.File;
import java.net.URLEncoder;
import java.io.*;
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;

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

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //處理請求  
        //讀取要下載的文件  
        String fileName = request.getParameter("file");
        //獲取項目的物理(磁盤)路徑
        String path = request.getSession().getServletContext().getRealPath("upload");
        //構造完整的文件路徑及文件名
        String filea = path + "/" +  fileName;
        
        System.out.println(filea);
        
        File f = new File(filea);  
        if(f.exists()){  
            FileInputStream  fis = new FileInputStream(f);  
            String filename=URLEncoder.encode(f.getName(),"utf-8"); //解決中文文件名下載后亂碼的問題  
            byte[] b = new byte[fis.available()];  
            fis.read(b);  
            response.setCharacterEncoding("utf-8");  
            response.setHeader("Content-Disposition","attachment; filename="+filename+"");  
            //獲取響應報文輸出流對象  
            ServletOutputStream  out =response.getOutputStream();  
            //輸出  
            out.write(b);  
            out.flush();  
            out.close();  
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM