Vista previa de la secuencia de archivos backend en el pdf del navegador

1. backend

capa de controlador:

    @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();
		}
	}

Clase de negocios:

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();
                }
            }
        }
    }

}

Dos, interfaz de 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)
      })
    },

3. Nota:

Si el tipo de retorno del backend es respuesta.setContentType("application/pdf");

Tipo de respuesta de front-end tipo de respuesta: "blob"

De lo contrario, habrá páginas en blanco y caracteres confusos.

Supongo que te gusta

Origin blog.csdn.net/yiye2017zhangmu/article/details/123546904
Recomendado
Clasificación