当前端利用pdf自带的加密方法加密时
后端直接取出来生成文件打不开,经过测试之后发现,因为base64位编码在72位字符之后会换行,,所以在获取到pdf转的编码之后需要在进行去除编码中的空格或换行的操作
下面是我接收编码之后的操作
public ResponseEntity<Object> pdf( HttpServletRequest req, HttpServletResponse res) throws Exception{
BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(),"UTF-8"));
String str = "";
String str2 = "";
String encoded="";
while((str = reader.readLine()) != null){//一行一行的读取body体里面的内容;
int i = str.indexOf(",");
str2=str.substring(i+1, str.length()); //去除编码前面因为pdf转而出现的多余的字符
encoded = str2.replaceAll("[\\s*\t\n\r]", "");//去除编码中的空格和换行
}
FileProperties.ElPath path = properties.getPath();//获取项目文件中配置的路径,关于pdf生成之后的路径
String pathUtl = path.getPathOut();
WordGeneratorUtils.convertBase64ToFile(encoded,pathUtl,"PDF");
return new ResponseEntity<>(encoded, HttpStatus.OK);
}
public static File convertBase64ToFile(String wholeStr, String pathUtl, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
String pathWay = pathUtl+"PDF"+File.separator;
File dir = new File(pathWay);
if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
dir.mkdirs();
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] bfile = decoder.decodeBuffer(String.valueOf(wholeStr));
file = new File(pathWay + File.separator + fileName+".pdf");
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
return file;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}