上传文件对于开发者来说是一件令人头痛的问题,特别是移动开发端,今天我就来分享一种android客户端快速上传文件到java服务器的方法但是这种方法只适合于小文件上传,如果是比较大的文件可能会造成内存溢出问题(这个问题可采用分段上传解决),服务器我用的是spring-mvc框架。
android 端:
public static String fileToBase64(File file) {
String base64 = null;
InputStream in = null;
try {
in = new FileInputStream(file);
byte[] bytes = new byte[in.available()];
int length = in.read(bytes);
base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return base64;
}
java服务器端:
public static File base64ToFile(String base64, String fileName) {
File file= null;
FileOutputStream out = null;
try {
// 解码,然后将字节转换为文件
String path = "f:/img";
file= new File(path, fileName);
if (!file.exists()) { // 文件夹
file.createNewFile();
}
byte[] bytes = new BASE64Decoder().decodeBuffer(base64);
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
byte[] buffer = new byte[1024];
out = new FileOutputStream(file);
int bytesum = 0;
int byteread = 0;
while ((byteread = in.read(buffer)) != -1) {
bytesum += byteread;
out.write(buffer, 0, byteread); // 文件写操作
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}