上傳圖片到第三方的url路徑:前端
前端代碼:redis
<form method="post" enctype="multipart/form-data" id="fileUploadFrom"> <img id="demo1" th:src="@{/images/u20.png}"/> </form> <div id="getOfMinImageDataId" style="margin: 10px 0px;"></div>
/*上傳圖片開始*/ layui.use("upload", function () { var upload = layui.upload; upload.render({ elem: '#fileUploadFrom' //綁定元素 , url: '/yuntian/upload' //上傳接口 [[@{/upload/img}]] , before: function (obj) { //預讀本地文件示例,不支持ie8 obj.preview(function (index, file, result) { $('#demo1').attr('src', result); //圖片連接(base64) file_base64 = "file_base64=" + $("#demo1").attr("src").split(',')[1];//獲得base64 console.log(file_base64) }) }, done: function (res, index, upload) { var data = res; var list = data.data;var imageData; var minImageHtml = ""; for (var i = 0; i < list.length; i++) { imageData = list[i].imageData; imageData="http://68.174.64.20"+imageData; minImageHtml += `<img src="${imageData}" minImageId="${list[i].id}" class="getOfMinImageDataIdClass">`; } //將結果集和小圖追加到上傳的那個圖片的下面 $("#getOfMinImageDataId").empty().append(minImageHtml); //給小圖建立點擊事件,用戶點擊選中圖片 $(".getOfMinImageDataIdClass").unbind('click').bind('click', function () { $(".getOfMinImageDataIdClass").removeClass('checkimg'); $(this).addClass('checkimg'); }) } })
.getOfMinImageDataIdClass { width: 65px; height: 65px; margin: 0px 2px; } .checkimg{ border:solid 2px orange; }
控制層:spring
@Controller @RequestMapping("/yuntian") @ResponseBody public class DataAccessController { @Autowired private DataAccessImpl dataAccess; @RequestMapping(value = "/upload", method = RequestMethod.POST) public JSONObject upload(@RequestParam(value="file",required=false)MultipartFile file, HttpSession session, HttpServletRequest request) throws IOException { return dataAccess.getOfMinImageData(file, session, request); } }
service:json
@Override /*根據上傳的圖片獲取小圖的數據*/ public JSONObject getOfMinImageData(MultipartFile file, HttpSession session, HttpServletRequest request) throws IOException { String id = uploadImage(file, session, request); System.out.println("獲得的id,打印看看:" + id); Map<String, String> headMap = new HashMap<>(); String url = "http://" + ip + ":" + port + "/api/image/"; headMap.put("Authorization", "Bearer" + " " + token()); headMap.put("Content-Type", "application/json;charset=UTF-8"); String result = httpRequestGetService.doGetRequestStringParam(url, headMap, id); JSONObject resultObject = (JSONObject) JSONObject.parse(result); return resultObject; }
/*上傳圖片*/ public String uploadImage(MultipartFile file, HttpSession session, HttpServletRequest request) throws IOException { String url = "http://" + ip + ":" + port + "/api/image/upload/"; Map<String, String> headMap = new HashMap<>(); String authorization = "Bearer " + token(); headMap.put("Authorization", authorization); String result = httpRequestPostService.doPostHttpRequestMultiValueMap(url, file.getBytes(), headMap); JSONObject resultObject = (JSONObject) JSONObject.parse(result); JSONObject data = resultObject.getJSONObject("data"); String id = (String) data.get("id"); redisUtil.set("uploadImageId", id); return id; }
上面的url是第三方接收圖片的url路徑api
@Override public String doPostHttpRequestMultiValueMap(String url, byte[] param, Map<String, String> headerMap) { HttpHeaders headers = new HttpHeaders(); //添加請求頭 for (Map.Entry<String, String> header : headerMap.entrySet()) { headers.add(header.getKey(), header.getValue()); } ByteArrayResource resource = new ByteArrayResource(param) { @Override public String getFilename() throws IllegalStateException { return String.valueOf(new Date().getTime()) + ".jpg"; } }; MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>(); map.add("file", resource); org.springframework.http.HttpEntity request = new org.springframework.http.HttpEntity(map, headers); RestTemplate template = new RestTemplate(); String body = template.postForEntity(url, request, String.class).getBody(); System.out.println("body:" + body); return body; }
doGetRequestStringParam:
public String doGetRequestStringParam(String url, Map<String, String> headMap, String param) { // 獲取鏈接客戶端工具 CloseableHttpClient httpClient = HttpClients.createDefault(); String entityStr = null; CloseableHttpResponse response = null; try { /* * 因爲GET請求的參數都是拼裝在URL地址後方,因此咱們要構建一個URL,帶參數 */ URIBuilder uriBuilder = new URIBuilder(url); // 根據帶參數的URI對象構建GET請求對象 HttpGet httpGet = new HttpGet(uriBuilder.build() + param); System.out.println("調用String參數的URL:" + httpGet); /* * 添加請求頭信息 */ for (Map.Entry<String, String> header : headMap.entrySet()) { httpGet.addHeader(header.getKey(), header.getValue()); } closeHttpUtil.setTimeOut(httpGet); System.out.println("GET請求路徑:"+httpGet); response = httpClient.execute(httpGet); // 得到響應的實體對象 HttpEntity entity = response.getEntity(); // 使用Apache提供的工具類進行轉換成字符串 entityStr = EntityUtils.toString(entity, "UTF-8"); System.out.println("GET請求返回的結果:"+entityStr); } catch (ClientProtocolException e) { System.err.println("Http協議出現問題"); e.printStackTrace(); } catch (ParseException e) { System.err.println("解析錯誤"); e.printStackTrace(); } catch (URISyntaxException e) { System.err.println("URI解析異常"); e.printStackTrace(); } catch (IOException e) { System.err.println("IO異常"); e.printStackTrace(); } finally { // 釋放鏈接 closeHttpUtil.close(response, httpClient); } return entityStr; }