写的一小段关于下载的代码,能够正常下载,但是文件的名字成了类的名字,却不是我定义的文件名,不知为何,只知道是编码的问题,但不知如何解决!- package cn.itcast.response;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import java.net.URLEncoder;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class ResponseDemo2 extends HttpServlet {
- //文件下载
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String path=this.getServletContext().getRealPath("/download/书画.jpg");
- String name=path.substring(path.lastIndexOf("\\")+1);
- //如果下载文件是中文文件,则文件需要经过URL编码
- response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(name,"UTF-8"));
- InputStream in=null;
- OutputStream out=null;
- try{
- in=new FileInputStream(path);
- int len=0;
- byte[] buffer=new byte[1024];
- out=response.getOutputStream();
- while((len=in.read(buffer))>0){
- out.write(buffer,0,len);
- }
- }finally{
- try{
- if(in!=null){
- in.close();
- }
- }catch(IOException e){
- e.printStackTrace();
- }
- try{
- if(out!=null){
- out.close();
- }
- }catch(IOException e){
- e.printStackTrace();
- }
- }
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request,response);
- }
- }
复制代码 |