servlet下載文件實現(xiàn)代碼詳解(五)
更新時間:2017年09月30日 16:30:27 作者:柳暗花明睡一覺
這篇文章主要為大家詳細介紹了servlet下載文件的實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了servlet下載文件的具體代碼,供大家參考,具體內(nèi)容如下
1.servlet下載文件
servlet下載文件就是將服務(wù)器端的文件傳輸?shù)娇蛻舳恕?/p>
2案例
下載文件servlet類
package com.learn;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by Administrator on 2017/09/24.
*/
public class DownLoadServlet extends HttpServlet {
private String filePath;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
filePath = config.getInitParameter("filePath");
//初始化路徑
//filePath = config.getServletContext().getRealPath(filePath);
System.out.println("初始化文件路徑:"+filePath);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
OutputStream out; //輸出流
InputStream in; //輸入流
String fileName = req.getParameter("fileName");
System.out.println("文件名稱:"+fileName);
//如果把文件名為null則提示用戶
if(fileName == null){
out = resp.getOutputStream();
out.write("please input fileName".getBytes());
out.close();
}
//獲取文件流
in = getServletContext().getResourceAsStream(filePath+ File.separator+fileName);
System.out.println(in==null?true:false);
int length = in.available();
//設(shè)置返回消息頭部信息
resp.setContentType("application/force-download");
resp.setHeader("Content-Length",String.valueOf(length));
resp.setHeader("content-disposition","attachment;filename=\""+fileName+"\"");
//輸出文件到客戶端
out = resp.getOutputStream();
int bytesend = 0 ;
byte[] buff = new byte[512];
while ((bytesend = in.read(buff))!= -1){
out.write(buff,0,bytesend);
}
in.close();
out.close();
}
}
web.xml配置
<servlet>
<servlet-name>download</servlet-name>
<servlet-class>com.learn.DownLoadServlet</servlet-class>
<init-param>
<param-name>filePath</param-name>
<param-value>file</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>download</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
您可能感興趣的文章:
相關(guān)文章
java開發(fā)SSM框架具有rest風格的SpringMVC
這篇文章主要介紹了java開發(fā)中如何使SSM框架具有rest風格的SpringMVC實現(xiàn)解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10
SpringMVC DispatcherServlet組件實現(xiàn)解析
這篇文章主要介紹了SpringMVC DispatcherServlet組件實現(xiàn)解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-03-03
Java連接數(shù)據(jù)庫oracle中文亂碼解決方案
這篇文章主要介紹了Java連接數(shù)據(jù)庫oracle中文亂碼解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-05-05
SpringBoot指標監(jiān)控功能實現(xiàn)
這篇文章主要介紹了SpringBoot指標監(jiān)控功能實現(xiàn),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-06-06

