android利用base64快速上传文件到javaweb服务

     上传文件对于开发者来说是一件令人头痛的问题,特别是移动开发端,今天我就来分享一种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;  
    }  


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值