MultipartFile上传图片的写法,记录一下。

上传图片到第三方的url路径:

前端代码:

<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;
}

 

 控制层:

@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:

 @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路径

 @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;
    }

 

posted @ 2019-08-09 18:07  汪全意  阅读(4011)  评论(0编辑  收藏  举报