java - 上传Pdf文件未在android中转换为base64
问题描述
我无法将 pdf 文件转换为 base64 字符串,但是当我打开 pdf 文件时文件上传成功,它显示 0kb 文件大小。相同的代码适用于图像,但是当我尝试用于转换为 pdf 文件时,它不起作用。在我的代码中,我创建了一个名为“NewBase64”的方法,我正在将 pdf 文件转换为 base64,任何人都可以告诉我哪里出错了,请帮助我。
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
private int PICK_IMAGE_REQUEST = 1;
VolleyAppController volleyAppController;
mydb db;
public static String url = "http://xxx.xxx.x.x:xx/Android_Service.asmx/UploadPDFFile";
int SELECT_MAGAZINE_FILE = 1;
private File myFile;
String encodeFileToBase64Binary = "";
private String NewBase64(String Path) {
String encoded = "";
try {
File file = new File(Path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos = new ObjectOutputStream(bos);
oos.writeObject(file);
bos.close();
oos.close();
byte[] bytearray = bos.toByteArray();
encoded = Base64.encodeToString(bytearray, Base64.DEFAULT);
} catch (Exception ex) {
}
return encoded;
}
private void uploadImage() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected Map<String, String> getParams() throws AuthFailureError {
String image = null;
image = NewBase64(encodeFileToBase64Binary);
String name1 = name.getText().toString().trim();
Map<String, String> params = new Hashtable<String, String>();
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name1);
return params;
}
};
}
解决方案
您可以使用以下方法将 PDF 转换为 base64
public String NewBase64(File mfile) {
ByteArrayOutputStream output = null;
try {
InputStream inputStream = null;
inputStream = new FileInputStream(mfile.getAbsolutePath());
byte[] buffer = new byte[8192];
int bytesRead;
output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
output64.close();
} catch (IOException e) {
e.printStackTrace();
}
return output.toString();
}
推荐阅读
- calculated-columns - 如何在spotfire中创建一阶导数计算列
- inno-setup - 在 Inno Setup Pascal 脚本中声明变量
- javascript - 如何阻止客户端从控制台调用 ajax 函数?
- python - 抓取需要提交表单的 php 网页
- python - Python 使用 JSON 对数据进行排序
- java - SSH 服务器-客户端通信,来自套接字的读写流
- javascript - SVG onclick 事件未在 iOS 设备上触发
- docker - 如何为不属于亚马逊估算器的 Sagemaker 创建 docker 映像以创建端点?
- python - 计数和突出显示问题
- javascript - 在 AJAX 请求之后,如何使用反应上下文 api 值更新 Formik 初始值?