jsp文件下载功能实现代码(jsp文件名命名规范)太疯狂了

随心笔谈9个月前发布 admin
71 0


package cn.jbit.download.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadOfIOServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String basePath=request.getSession().getServletContext().getRealPath(“/upload”);

String filedisplay=”helloworld.jpg”;
String filedownload=basePath + File.separator + “helloworld.jpg”;
response.setContentType(“applicaiton/x-download”);
response.addHeader(“Content-Disposition”, “attachment;filename=”+filedisplay);

InputStream is=null;
OutputStream os=null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;

is=new FileInputStream(new File(filedownload));
bis=new BufferedInputStream(is);
os=response.getOutputStream();
bos=new BufferedOutputStream(os);

byte[] b=new byte[1024];
int len=0;
while((len=bis.read(b)) !=-1){
bos.write(b,0,len);
}

bis.close();
is.close();
bos.close();
os.close();
}
}

© 版权声明

相关文章