Base64编码格式上传多文件

本文介绍如何利用Base64编码技术处理多文件上传。内容涉及导入相关包,Controller层的代码实现,以及JSON转换的Maven依赖项。

导入的包

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值