我无法将pdf文件转换为base64字符串,但是当我打开显示0kb文件大小的pdf文件时,文件上传成功。相同的代码适用于图像,但是当我尝试用于转换为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;
}
};
}
答案 0 :(得分:0)
您可以使用以下方法将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();
}