一、下載連接jsp界面(a連接直接鏈文件能夠看出文件在服務器中的路徑,用servlet處理的連接則看不出)html
<%@ 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錯誤,由於中文亂碼了,因此找不到文件,解決方案:java
在tomcat中指定url編碼便可,找到tomcat目錄中的conf下的server.xml,而後打開,找到端口的配置的標籤位置:tomcat
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
而後加上URIEncoding="UTF-8"這個配置,從新啓動tomcat便可(上面代碼我已加上)
摘:http://ykyfendou.iteye.com/blog/2094734服務器
二、DownloadServlet處理代碼jsp
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(); } } }