標籤:attach time rar att 處理 const ring isp 方案
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(); } }}
jsp中的下載連結