java中一個簡單的下載樣本

來源:互聯網
上載者:User

標籤:

首先在tomcat伺服器下的webapps的download項目下建一個doc檔案夾,再建個test.doc.防止控指標異常

DownLoad.java代碼

 1 package com.down; 2  3 import java.io.IOException; 4 import java.io.InputStream; 5  6 import javax.servlet.ServletException; 7 import javax.servlet.ServletOutputStream; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet;10 import javax.servlet.http.HttpServletRequest;11 import javax.servlet.http.HttpServletResponse;12 13 @WebServlet(14         name="download",15         urlPatterns={"/test"}16         )17 public class DownLoad extends HttpServlet {18     @Override19     protected void doPost(HttpServletRequest req, HttpServletResponse resp)20             throws ServletException, IOException {21         doGet(req, resp);22     }23     @Override24     protected void doGet(HttpServletRequest request, HttpServletResponse response)25             throws ServletException, IOException {26         response.setContentType("application/msword");27         response.addHeader("Content-disposition","attachment;filename=test.doc");28         InputStream in=getServletContext().getResourceAsStream("/doc/test.doc");29         ServletOutputStream os=response.getOutputStream();30         byte[] bytes=new byte[1024];31         int len=-1;32         while((len=in.read(bytes))!=-1){33             os.write(bytes,0,len);34         }35         in.close();36         os.close();37     }38 }

運行結果:

java中一個簡單的下載樣本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.