经常看到很多新手在初次给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";
}
}
@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 或者点击
下载