接收base64编码解码,并保存图片

接收类
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;

/**
 * 接受文件
  * <p>Title : AcceptFileController</p>
  * <p>Description : </p>
  * <p>DevelopTools : Eclipse_x64_v4.8.1</p>
  * <p>DevelopSystem : Windows 10</p>
  * <p>Company : org.wcy</p>
  * @author : WangChenYang
  * @date : 2018年10月8日 下午2:04:18
  * @version : 0.0.1
 */
@Controller
public class AcceptFileController {

	/**
	 * 储存文件
	 * @param data 图片的md5,图片后缀,图片的base64
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("upload")
	@ResponseBody
	public JSONObject upload(HttpServletRequest request,@RequestBody byte[] data) throws UnsupportedEncodingException, IOException{
        Map<String, String> map = new HashMap<>();

        //---------此接受方法限于springmvc--------------start---mvc
        //参数接收
        //DataInputStream in = new DataInputStream(request.getInputStream());
        //byte[] bts = new byte[1024];
        //int len = -1;
        //StringBuffer sb = new StringBuffer();
        //while((len = in.read(bts)) != -1) {
        //    String x=new String(bts, 0, len);
        //    sb.append(x);
        //}
        //in.close();
        //String parame = sb.toString();
        //---------此接受方法限于springmvc--------------end---mvc

        //---------springboot--------------start---mvc
        //在Springboot程序启动后,会默认添加OrderedCharacterEncodingFilter和HiddenHttpMethodFilter过滤器。
        // 在HiddenHttpMethodFilter过滤器中会调用request.getParameter(),
        // 从而造成我们在controller中通过request的InputStream无法读取到RequestBody的数据。
        String parame = new String(data);
        //---------springboot--------------end---mvc

        System.out.println(parame);

        String[] splitResult = parame.split("&");
        for (String string : splitResult) {
            map.put(string.substring(0, string.indexOf("=")), string.substring(string.indexOf("=")+1));
        }

        //计算完整路径
        String rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1)+"static/upload/";
        boolean judge = FileCopyUtil.base64ToFile(map.get("image"), new File(rootPath+map.get("md5ByFile")+"."+map.get("postfix")));
        JSONObject json = new JSONObject();
        String localhost = request.getScheme()+"://127.0.0.1:"+request.getServerPort()+request.getContextPath()+"/upload/";
        json.put("result", judge+"");
        json.put("imgURL", localhost);
        return json;
	}
}

储存类

import org.apache.tomcat.util.codec.binary.Base64;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


/**
 * 流拷贝
  * <p>Title : FileUtil</p>
  * <p>Description : </p>
  * <p>DevelopTools : Eclipse_x64_v4.8.1</p>
  * <p>DevelopSystem : Windows 10</p>
  * <p>Company : org.wcy</p>
  * @author : WangChenYang
  * @date : 2018年9月25日 上午12:39:14
  * @version : 0.0.1
 */
public class FileCopyUtil {
	
	/**
	 * base64转File
	 * @param base64
	 * @param dest
	 */
	public static boolean base64ToFile(String base64,File dest) {
		BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //由于base64在传输过程中,+和/和=会被替换所以在解码前需要将base64还原成可用的base64
            base64 = base64.replaceAll(" ","+");
            base64 = base64.replaceAll("%2F","/");
            base64 = base64.replaceAll("%3D","=");
            //当使用springMVC时无需使用以上方法进行还原

            byte[] bytes = Base64.decodeBase64(base64.replace("\r\n", ""));
            bis = new BufferedInputStream(new ByteArrayInputStream(bytes));
            bos = new BufferedOutputStream(new FileOutputStream(dest));
            byte[] bts = new byte[1024];
            int len = -1;
            while((len = bis.read(bts)) != -1) {
            	bos.write(bts,0,len);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                	bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
	
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值