接收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();
                }
            }
        }
    }
	
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章