1. 程式人生 > >web---資源的下載及中文亂碼問題

web---資源的下載及中文亂碼問題

cte 問題 處理 javax except 找不到 註冊 exce lan

1、html網頁,超鏈接交由Servlet處理

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>實現文件的下載功能</h1>
    <a href="ImgServlet?filename=a.jpg">aa</a><br>
    <a href="ImgServlet?filename=b.jpg
">bb </a><br> <a href="ImgServlet?filename=圖片.png">圖片</a><br> </body> </body> </html>

2.web.xml----Servlet的註冊

    <servlet>
        <servlet-name>DownLoadImgServlet</servlet-name>。--1
        <servlet-class>nee.DownLoadImgServlet</servlet-class
> --這是我自己的路徑 </servlet> <servlet-mapping> <servlet-name>DownLoadImgServlet</servlet-name>--2 <url-pattern>/ImgServlet</url-pattern>--網頁的映射,對應html上a的超鏈接 </servlet-mapping>
--1 2 處名字必須相同

3.Servlet的實現

package nee;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@WebServlet(name 
= "DownLoadImgServlet") public class DownLoadImgServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* 用字節輸出流向文件寫資源 資源需要從輸入流中讀入 輸入流為圖片構成的輸入流 */ String filename=request.getParameter("filename"); //解決中文找不到資源路徑的問題 filename = new String(filename.getBytes("ISO-8859-1"),"UTF-8"); //將文件轉化為輸入流 InputStream is=getServletContext().getResourceAsStream("download/"+filename); //解決文件名不顯示中文的問題 filename=URLEncoder.encode(filename,"UTF-8"); //聲明這是一個下載的文件 response.setHeader("Content-Disposition","attachment;filename="+filename); OutputStream os=response.getOutputStream(); int len=0; byte[] buffer = new byte[1024]; while ((len=is.read(buffer) )!= -1){ os.write(buffer,0,len); } } }

web---資源的下載及中文亂碼問題