后端文件流在浏览器pdf预览

一.后端

controller层:

    @ResponseBody
	@AutoLog(value = "跳转文档")
	@ApiOperation(value = "跳转文档", notes = "跳转文档")
	@PostMapping("/getEnergyDoc")
	public void result(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String pdfPath = System.getProperty("user.dir") + "/使用手册.pdf";
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/pdf");
		response.setHeader("Content-Disposition", "使用手册.pdf");
		FileUtils.writeBytes(pdfPath, response.getOutputStream());
		File file = new File(pdfPath);
		if (file.exists()) {
			DataOutputStream temps = new DataOutputStream(response.getOutputStream());
			DataInputStream in = new DataInputStream(new FileInputStream(pdfPath));
			byte[] b = new byte[2048];
			while ((in.read(b)) != -1) {
				temps.write(b);
				temps.flush();
			}
			in.close();
			temps.close();
		}
	}

业务类:

public class FileUtils {

	 /**
     * 输出指定文件的byte数组
     * 
     * @param filePath 文件路径
     * @param os 输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException
    {
        FileInputStream fis = null;
        try
        {
            File file = new File(filePath);
            if (!file.exists())
            {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
        }
        catch (IOException e)
        {
            throw e;
        }
        finally
        {
            if (os != null)
            {
                try
                {
                    os.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (fis != null)
            {
                try
                {
                    fis.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }
    }

}

二.vue前端:

//get
export function getFileAction(url,parameter) {
  return axios({
    url: url,
    responseType:"blob",
    method: 'post',
    params: parameter
  })
}
wordDetail() {
      // 微软提供的方法
      getFileAction('/test/getEnergyDoc').then((res) => {
        let url = window.URL.createObjectURL(res)
        window.open(url)
      })
    },

三.注意:

后端返回类型要是response.setContentType("application/pdf");

前端响应类型responseType:"blob"

不然会出现空页、乱码现象

猜你喜欢

转载自blog.csdn.net/yiye2017zhangmu/article/details/123546904