本文共 2876 字,大约阅读时间需要 9 分钟。
@RequestMapping("download") public ResponseEntitydownload(String filePath, int id) throws IOException { client = dcf.createClient(WSDL_URL); FileDecryptVo fileDecryptVo=null; try { objects = client.invoke("getFileDecryptById", id); String json = (String) objects[0]; fileDecryptVo = JSON.parseObject(json, FileDecryptVo.class); } catch (Exception e) { e.printStackTrace(); } assert fileDecryptVo != null; String filepath =fileDecryptVo.getFilePath(); File file=new File(filepath); String fileName=new String(filepath.split("\\\\")[2].getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); HttpHeaders headers = new HttpHeaders(); fileName=new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); headers.setContentDispositionFormData("attachment", fileName); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity (FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); }
@RequestMapping(value = "/download", method = RequestMethod.GET) public void download(HttpServletResponse res, int id) { client = dcf.createClient(WSDL_URL); FileDecryptVo fileDecryptVo = null; try { objects = client.invoke("getFileDecryptById", id); String json = (String) objects[0]; fileDecryptVo = JSON.parseObject(json, FileDecryptVo.class); } catch (Exception e) { e.printStackTrace(); } assert fileDecryptVo != null; String filepath = fileDecryptVo.getFilePath(); res.setContentType(MediaType.TEXT_PLAIN_VALUE); //UTF_8是项目编码,ISO_8859_1是浏览器默认编码。 String fileName = new String(filepath.split("\\\\")[2].getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); res.setHeader("Content-Disposition", "attachment;filename=" + fileName); byte[] buff = new byte[2048]; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis =new BufferedInputStream(new FileInputStream(new File(filepath))) ; bos = new BufferedOutputStream(res.getOutputStream()); int readLength=0; while ((readLength=bis.read(buff))!= -1) { bos.write(buff, 0, readLength); bos.flush(); } } catch (IOException e) { e.printStackTrace(); } finally { try { assert bis != null; bis.close(); assert bos != null; bos.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("success"); }
转载地址:http://owgai.baihongyu.com/