java基础(三--2) 附件以流的形式返回前端

import java.io.*; import java.net.URLEncoder; 
import javax.servlet.ServletOutputStream; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse;
public void downloadFileStream(HttpServletResponse response,  String fileUrl) {
  try {
          if(StringUtils.isNoneBlank(fileUrl)) {
              File file = new File(fileUrl);
              String filename = file.getName();
              // 以流的形式下载文件。
              InputStream fis = new BufferedInputStream(new FileInputStream(fileUrl));
              byte[] buffer = new byte[fis.available()];
              fis.read(buffer);
              fis.close();
              // 清空response
              response.reset();
              response.setContentType("application/octet-stream;charset=UTF-8");
              String fileName = new String(filename.getBytes("gb2312"), "iso8859-1");
              response.setHeader("Content-disposition", "attachment;filename=" + fileName);
              OutputStream ouputStream = response.getOutputStream();
              ouputStream.write(buffer);
              ouputStream.flush();
              ouputStream.close();
          }
           } catch (Exception e) {
               e.printStackTrace();
               logger.error("文件下载出现异常", e);
           }
}

你可能感兴趣的:(java基础,java)