Android Base64上传图片到 SpringMVC服务器

本文介绍Base64编码的概念及应用,详细解释了如何在Java后端接收并解析Base64编码的图片文件,实现从app端上传到服务器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     经常看到很多新手在初次给app端写上传接口时,都很迷茫,不知道如何与app端交互,今天就为大家讲解如果接收app端传来的文件首先我们应该了解什么是base64。

base64

  编辑
Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045~RFC2049,上面有MIME的详细规范。Base64编码可用于在HTTP环境下传递较长的标识信息。例如,在Java Persistence系统Hibernate中,就采用了Base64来将一个较长的唯一标识符(一般为128-bit的UUID)编码为一个字符串,用作HTTP表单和HTTP GET URL中的参数。在其他应用程序中,也常常需要把二进制数据编码为适合放在URL(包括隐藏表单域)中的形式。此时,采用Base64编码具有不可读性,即所编码的数据不会被人用肉眼所直接看到。
由以上定义可以看出我们只需要接收前端传过来的字节码文件,再进行相应的解码就可以了,下面来看一组服务端代码。
package com.springmvc.upload;
import sun.misc.BASE64Decoder;
@Controller
@RequestMapping("/androidUser")
public class UserHandler {
@ResponseBody
@RequestMapping(value = "/imageUpload")
public Object imageUpload(@RequestParam(value = "photo") String photo,String actiontype, @RequestParam(value = "userId") String userId, HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
Map<String, Object> map = new HashMap<String, Object>();
System.out.println("userId:"+userId);
System.out.println("photo:"+photo);
try {


// 对base64数据进行解码 生成 字节数组,不能直接用Base64.decode();进行解密
byte[] photoimg = new BASE64Decoder().decodeBuffer(photo);
for (int i = 0; i < photoimg.length; ++i) {
if (photoimg[i] < 0) {
// 调整异常数据
photoimg[i] += 256;
}
}
// 获取项目运行路径
String pathRoot = request.getSession().getServletContext().getRealPath("")+"/images/";
File dir= new File(pathRoot);
if  (!dir .exists() && !dir .isDirectory())      
{       
   System.out.println("//不存在");  
   dir .mkdir();    
}
// 生成uuid作为文件名称
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String path =uuid + "head.png";
// byte[] photoimg =
// Base64.decode(photo);//此处不能用Base64.decode()方法解密,我调试时用此方法每次解密出的数据都比原数据大
// 所以用上面的函数进行解密,在网上直接拷贝的,花了好几个小时才找到这个错误(菜鸟不容易啊)
System.out.println("图片的大小:" + photoimg.length);
File file = new File(pathRoot + path);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream out = new FileOutputStream(file);
out.write(photoimg);
out.flush();
out.close();
map.put("updateImage", "filed");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Success";
}
}
以上为服务端代码,完整的android和服务端代码请去http://download.youkuaiyun.com/detail/prefect2012/9769675 或者点击 下载


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值