Web 簡單檔案下載

來源:互聯網
上載者:User

標籤:開始   chm   throws   session   on()   close   res   servlet   header   

  最近開始做第一個項目,在做檔案下載的方面遇到了一點問題,現在在這裡分享一下。

  對於檔案下載,我一開始的做法是讀取了資料庫中的需要下載的檔案的相對於工程的相對路徑後賦值給html代碼的a標籤的href屬性,但是在測試的時候發現像txt、docx這類文字文件並不是提示下載,而是將相應的檔案直接開啟了,而由於編碼的不同,就出現了滿屏亂碼這種情況,後來瞭解到是瀏覽器對這類簡單的檔案,它本身能夠解析的檔案類型都會直接開啟顯示,只有那些瀏覽器無法識別解析的檔案類型才會提示使用者下載,後來我的解決方案是寫了一個下載的servlet類,代碼如下:

public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        PrintWriter out;        //接收參數,path表示當前檔案相對項目根目錄的相對路徑        String path = request.getParameter("path");        //擷取檔案的絕對路徑        String filepath = request.getSession().getServletContext().getRealPath(path);        File file = new File(filepath);        //判斷該檔案是否存在        if(!file.exists()) {            out = response.getWriter();            out.println("<script>alert(\"檔案不存在!\");window.history.back()</script>");            out.close();return;        }        response.addHeader("content-disposition", "attachment;filename=" + path);        IOUtils.copy(new FileInputStream(file), response.getOutputStream());    }

 

Web 簡單檔案下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.