zl程序教程

您现在的位置是:首页 >  其他

当前栏目

HttpClient上传文件传入MultipartFile类型

2023-04-18 12:32:30 时间

通常我们在使用httpclient的时候,一把都是使用get或者postd的方式传输一些数据。在近期的项目中有这样的一个需求,我需要通过httpclient去调用一个写好的文件上传的接口,接口中是使用MultipartFile 来接受文件类型参数的。在这种情况下我们就开辟一个HttpClient中的高级功能了。直接上代码,封装了一个工具类:

 /**
     * 使用httpclint 发送文件
     * @author: qingfeng
     * @date: 2019-05-27
     * @param file
     *            上传的文件
     * @return 响应结果
     */
    public static String uploadFile(String url ,MultipartFile file,String fileParamName,Map<String,String>headerParams,Map<String,String>otherParams) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            String fileName = file.getOriginalFilename();
            HttpPost httpPost = new HttpPost(url);
            //添加header
            for (Map.Entry<String, String> e : headerParams.entrySet()) {
                httpPost.addHeader(e.getKey(), e.getValue());
            }
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(Charset.forName("utf-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题
            builder.addBinaryBody(fileParamName, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            for (Map.Entry<String, String> e : otherParams.entrySet()) {
                builder.addTextBody(e.getKey(), e.getValue());// 类似浏览器表单提交,对应input的name和value
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

要注意,这种情况下,一旦对方返回的结果中存在中文有可能出现乱码,解决方法就是向上面的代码中加入:

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题、

解决浏览器兼容问题。 这样就可以顺利得到返回值了

调用案例:

 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
 List<MultipartFile> files = multipartRequest.getFiles("repayFile");//从request中获取前端穿过来的文件

//调用httpclient
 String res = HttpUtil.uploadFile("localhost:8080/upload", files.get(0), "repayFile", headers, paramMap);

上传文件的接口:

@RequestMapping(value = "/upload", method = {RequestMethod.POST })
	public void fileBatchRepay(
			@RequestParam(value = "repayFile") MultipartFile repayFile,
			@RequestParam(value = "type") String type) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<List<String>> list=new ArrayList<List<String>>();
	    try {
			list = borrowRepayService.fileBatchRepay(repayFile,type);
	    	String title = "exel模板demo";
	    	RepayExcelModel report = new RepayExcelModel();
			String fileName = report.saveExcelByList(list, title, repayFile.getOriginalFilename(),request);
	    	result.put(Constant.RESPONSE_DATA, "/down.htm?path="+fileName);
	    	result.put(Constant.RESPONSE_CODE, Constant.SUCCEED_CODE_VALUE);
			result.put(Constant.RESPONSE_CODE_MSG, "获取成功");
		} catch (BussinessException e) {
			logger.error(e.getMessage(),e);
			result.put(Constant.RESPONSE_CODE, Constant.FAIL_CODE_VALUE);
			result.put(Constant.RESPONSE_CODE_MSG, e.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			result.put(Constant.RESPONSE_CODE, Constant.FAIL_CODE_VALUE);
			result.put(Constant.RESPONSE_CODE_MSG, "失败");
		}
	    ServletUtils.writeToResponse(response, result);
	}

好了,就分享到这里,希望对大家有帮助想学java的同学,也可以看我的java基础教学视频https://www.bilibili.com/video/av37413483?from=search&seid=16996396768466285203,免费学习