实现目的,主要是将 ntko editoffice.jsp intializePage(url) 下的url改成从本地地址,改成可以返回二进制文档流的后台接口地址。
令人奇怪的是不管怎么弄,ntko总是会跳出文件存取错误的窗口,数据流postman看过了没问题,路径后台显示已经访问成功了。
解决方案:
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
添加这行,代码设置response编码格式。按理说,问题就应该解决了,但我这一行代码写在了response.getOutputStream后面了,结果出现和正确代码相似99%,但问题依然在的情况。
后来发现,response光有.addHeader("Content-Disposition")还不行,还需要写在response.setContentType()前面,写在后面就会出错。那个如果是要写在后面的话是用.setHeader可以通过,原因应该是response.setContentType方法同时已经设置了header了,需要用setHeader来覆盖。这个坑有点深,我半天爬不出来。
最后代码:
控制器部分:
public void getWord (String fileNameDisk, HttpServletResponse response){try{System.out.println(fileNameDisk);System.out.println("=============生成word数据=================");byte[] data=service1.getWordBytes(fileNameDisk);System.out.println("=============添加到response===============");response.addHeader("Content-Disposition","attachment;filename="+new String(fileNameDisk.getBytes()));//这个很重要不加会出错response.addHeader("Content-Length",""+data.length);//这个要放在前面response.setContentType("multipart/form-data");OutputStream out=new BufferedOutputStream(response.getOutputStream());out.write(data);out.flush();out.close();
// response.setCharacterEncoding("utf-8");
// response.setContentType("application/msword;charset=UTF-8");
// String header="attachment;filename="+fileNameDisk;
// response.addHeader("content-disposition",header);}catch(IOException e){e.printStackTrace();}}
sevice部分
public byte[] getWordBytes(String fileNameDisk) throws IOException{String url=FilePathInfo.absoluteOfficeFileDir+fileNameDisk;File f=new File(url);// byte[]result=new byte[(int) f.length()];FileInputStream fis=new FileInputStream(url);InputStream is=new BufferedInputStream(fis);byte[]result=new byte[is.available()];is.read(result);//用fis 和 is结果似乎差不多is.close();return result;}