1、HttpServletResponse response返回文件
//包装流
BufferedInputStream bfs = new BufferedInputStream(ips);
OutputStream os = response.getOutputStream();
byte[] a = new byte[1024];
int len;
while((len = bfs.read(a)) != -1){
os.write(a, 0, len);
}
os.flush();
ips.close();
bfs.close();
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
2、springboot文件下载,(文件读取字节数组转为base64格式的字符串,再转化为流)
@RequestMapping("/download") public ResponseEntity<InputStreamResource> download(String params, HttpServletResponse response){ RestTemplate restTemplate = new RestTemplate(); String url = ""; //MultiValueMap<String, String> map= new LinkedMultiValueMap<>(); //HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); ResponseEntity<String> rs = restTemplate.postForEntity(url, null, String.class); try { JSONObject jo = JSONObject.fromObject(rs.getBody()); if("true".equals(jo.getString("isend"))){ byte[] bytes = Base64.getDecoder().decode(jo.getString("content")); String fileName = jo.getString("name"); Long fileSize = jo.getLong("size"); ByteArrayInputStream ips = new ByteArrayInputStream(bytes); /*BufferedInputStream bfs = new BufferedInputStream(ips); OutputStream os = response.getOutputStream(); byte[] a = new byte[1024]; int len; while((len = bfs.read(a)) != -1){ os.write(a, 0, len); } os.flush(); ips.close(); bfs.close();*/ HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8")); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); return ResponseEntity .ok() .headers(headers) .contentLength(fileSize) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(new InputStreamResource(ips)); } else { int slice = jo.getInt("slice"); if(slice > 1){ for(int i = 2; i < slice; i++){ String urlsi = url + "?slice=" + i; ResponseEntity<String> re = restTemplate.postForEntity(urlsi, null, String.class); JSONObject jb = JSONObject.fromObject(re.getBody()); byte[] bt = Base64.getDecoder().decode(jb.getString("content")); } } } } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }