导入的包
import org.apache.tomcat.util.codec.binary.Base64;
import net.sf.json.JSONArray;
Controller层代码:
@SuppressWarnings("unchecked")
@RequestMapping("/uploadBase64")
public String uploadBase64(@RequestParam String fdContent,HttpServletRequest request,HttpServletResponse response) throws IOException {
if(fdContent != null && !"".equals(fdContent)) {
JSONArray jsonArray = JSONArray.fromObject(fdContent);
List<String> base64List = (List<String>) JSONArray.toCollection(jsonArray);
Map<byte[], String> dataMap = new HashMap<byte[], String>(); //键是文件解码后的数组,值是文件类型
for (String base64Code : base64List) {
String[] split = base64Code.replaceAll(" ", "+").split(",");//base64格式中的“+”在传参过程中会被替换为空格,需替换回来
byte[] decodeBase64 = Base64.decodeBase64(split[1]);
dataMap.put(decodeBase64, split[0]);
}
for (Entry<byte[], String> map : dataMap.entrySet()) {
String fileName = System.currentTimeMillis()+"_"+UUID.randomUUID()+getFileType(map.getValue());
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("D:/"+fileName));
fos.write(map.getKey());
fos.flush();
} catch (Exception e) {
return "上传失败!";
}finally {
if(fos != null) {
fos.close();
}
}
}
}
return "上传成功!";
}
/**
* 工具类获取base64编码文件的类型
* @param content
* @return
*/
public static String getFileType(String type) {
String suffix = ".jpg"; //默认jpg
if("data:image/png;base64".equals(type)) {
suffix = ".png";
}
if("data:image/bmp;base64".equals(type)) {
suffix = ".bmp";
}
if("data:image/gif;base64".equals(type)) {
suffix = ".gif";
}
if("data:text/plain;base64".equals(type)) {
suffix = ".txt";
}
return suffix;
}
JSON转换的maven依赖:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>