今天我们学的是文件下载和中文文件下载,下面是文件下载的代码:
package cn.csdn.web.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.imageio.stream.FileImageInputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Demo01Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*文件下载*/
/*要知道你下载的资源*/
ServletContext context=this.getServletContext();
String path= context.getRealPath("/WEB-INF/classes/res/许嵩.bmp");
/*构造文件*/
File file = new File(path);
/*构造文件的输入流*/
InputStream is= new FileInputStream(file);
/*写:输出流*/
/*文件的下载*/
response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(file.getName(), "UTF-8"));
OutputStream os= response.getOutputStream();
byte buffer[]=new byte[1024];
int len=0;
while((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
}
os.close();
is.close();
}
private void test(HttpServletResponse response) throws IOException,
UnsupportedEncodingException {
//response对象 因为getbytes获取的是gb2312的数据,而浏览器默认以gb2312的数据
// response.setHeader("Content-Type", "text/html;charset=UTF-8");
response.getOutputStream().write(" <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">".getBytes());
response.getOutputStream().write("中国".getBytes("UTF-8"));
response.getOutputStream().write((98+"").getBytes());
}