美文网首页
SpringMVC下载文件

SpringMVC下载文件

作者: 豪门百里 | 来源:发表于2016-11-30 11:44 被阅读41次

吐槽一下,当年的代码风格不够好,没写注释。之后如果要用到解读起来就有些麻烦了。希望不会再用到Java

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

@RequestMapping("downloadExport.do")
public ResponseEntity<byte[]> downloadExport() {
    byte[] body = null;
    HttpHeaders httpHeaders = new HttpHeaders();
    HttpStatus httpStatus = HttpStatus.OK;
    String webapp = System.getProperty("rootPath");
    String path = webapp + "/upload/StaffInfoExport.xls";
    String fileName = "StaffInfoExport.xls";
    File file = new File(path);
    try {
        InputStream inputStream = new FileInputStream(file);
        body = new byte[inputStream.available()];
        inputStream.read(body);
        inputStream.close();
    } catch (Exception e) {
        System.out.println(path);
        System.out.println(e.toString());
        return null;
    }
    
    httpHeaders.add("Content-Type", "application/vnd.ms-excel");
    httpHeaders.add("Content-Length", "" + body.length);
    httpHeaders.add("Content-Disposition", "attachment;filename=" + fileName);
    
    ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(body, httpHeaders, httpStatus);
    return responseEntity;
}

相关文章

网友评论

      本文标题:SpringMVC下载文件

      本文链接:https://www.haomeiwen.com/subject/yuttmttx.html