Java 文件下载

import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.context.ServletContextAware;  
  
import javax.servlet.ServletContext;  
import javax.servlet.ServletOutputStream;  
import javax.servlet.http.HttpServletResponse;  
import java.io.*;  
  
@Controller  
public class FileController implements ServletContextAware{  

    private ServletContext servletContext;  
   
    @RequestMapping("file/download")  
    public void fileDownload(HttpServletResponse response){  
     
        String path = servletContext.getRealPath("/");  

        response.setContentType("multipart/form-data");  
        response.setHeader("Content-Disposition", "attachment;fileName="+"xx.zip");  
        ServletOutputStream out;  
        //下载文件路径
        File file = new File(path + "download/" + "xx.zip");  
  
        try {  
            FileInputStream inputStream = new FileInputStream(file);  
  
           
            out = response.getOutputStream();  
  
            int b = 0;  
            byte[] buffer = new byte[512];  
            while (b != -1){  
                b = inputStream.read(buffer);  
                
                out.write(buffer,0,b);  
            }  
            inputStream.close();  
            out.close();  
            out.flush();  
  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
  
    @Override  
    public void setServletContext(ServletContext servletContext) {  
        this.servletContext = servletContext;  
    }  
}  

 

posted @ 2015-12-19 18:57  独孤黑狼  阅读(99)  评论(0编辑  收藏  举报