1.pdf转换base64
public static String encodeBase64File(String path) {
File file = new File(path);
byte[] buffer = new byte[(int) file.length()];
try {
FileInputStream inputFile = new FileInputStream(file);
inputFile.read(buffer);
inputFile.close();
} catch (IOException e) {
e.printStackTrace();
}
return Base64.encodeToString(buffer, Base64.DEFAULT);
}
2.上传
public void fileupload(Callback callback,String path,String serverUrl,String pdfPath) {
// File file = new File(path);
//String pdfbase64=NewBase64(file);
String pdfbase64=encodeBase64File(path);
OkHttpClient client = new OkHttpClient();
// 上传文件使用MultipartBody.Builder
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("pdfpath", pdfPath) // 提交普通字段
.addFormDataPart("filebase64", pdfbase64) // 提交图片,第一个参数是键(name="第一个参数"),第二个参数是文件名,第三个是一个RequestBody
.build();
// POST请求
Request request = new Request.Builder()
.url(serverUrl)
.post(requestBody)
.build();
client.newCall(request).enqueue(callback);
}
3.服务端接收转换
@RequestMapping("/save_pdf")
public void saveAztFile(HttpServletRequest request, ModelMap model, HttpServletResponse response, String filebase64,
String pdfpath) throws Exception {
SaveMsgEntity entity = new SaveMsgEntity();
entity.setCode("0");// 0失败 1成功
if (filebase64 != null && pdfpath != null && !filebase64.equals("") && !pdfpath.equals("")) {
try {
String localPath = "";
String filePath = "";
String basePath = Constants.UPLOAD_PATH + Constants.SOUND_PATH;
filePath = pdfpath.split("//")[2];
if (!filePath.equals("")) {
filePath = filePath.replace("/", "\\");
localPath = basePath + filePath;
}
/**
* 解码
*/
byte[] pdfbyte= new BASE64Decoder().decodeBuffer(filebase64);
/**
* 保存到pdf
*/
File file = new File(localPath);
FileUtils.writeByteArrayToFile(file, pdfbyte);
entity.setCode("1");// 0失败 1成功
entity.setMsg("保存成功!");
} catch (Exception e) {
entity.setMsg("保存pdf失败,请稍后重试!");
}
} else {
entity.setMsg("数据流和路径不能为空,请稍后重试!");
}
ResponseUtil.responseText(response, JSON.toJSONString(entity));
}
|