SpringMVC下载文件

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

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

@RequestMapping("downloadExport.do")
public ResponseEntity 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 responseEntity = new ResponseEntity(body, httpHeaders, httpStatus);
    return responseEntity;
}

你可能感兴趣的:(SpringMVC下载文件)