zoukankan      html  css  js  c++  java
  • SpringMVC下载文件

    import org.junit.Test;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    
    import javax.servlet.http.HttpSession;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    
    public class TestDownControlelr {
    
    
        @Test
        public ResponseEntity<byte[]> down(HttpSession session) throws IOException {
    
            //获取下载文件的路径
            String realPath = session.getServletContext().getRealPath("img");
            String finalPath = realPath + File.separator + "2.jpg";
            FileInputStream is = new FileInputStream(finalPath);
            //available(): 获取输入流所读取的文件的最大字节数
            byte[] b = new byte[is.available()];
            is.read(b);
    
            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition","attachment;filename=zzz.jpg");
            //设置响应状态
            HttpStatus statusCode = HttpStatus.OK;
            ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(b, headers, statusCode);
    
            return entity;
        }
    
    }
    
    
  • 相关阅读:
    2017年3月笔记
    2017年2月笔记
    2017年1月笔记
    2016年12月笔记
    2016年11月笔记
    2016年10月笔
    2016年9月笔记
    2016年8月笔记
    2016年7月笔记
    2016年6月笔记
  • 原文地址:https://www.cnblogs.com/KingTL/p/13033346.html
Copyright © 2011-2022 走看看