使用HTTP向远程接口发送文件上传请求------JAVA程序模拟前端表单上传文件

JAVA程序模拟前端表单上传文件

1、控制器代码

    @RequestMapping("/upload")
	@ResponseBody
	@SuppressWarnings("unchecked")
	public void startVideoAnalyze(HttpServletResponse response, 
	                              @RequestParam(value = "image") MultipartFile image)throws IOException {
		InputStream fileStream = image.getInputStream();
		String fileName = image.getOriginalFilename();
		String fileType = image.getContentType();
		// 发送请求:sys_url为自己的远程接口地址
		String jsonString = singleFileUploadWithParameters(sys_url, "img", fileStream, fileName, fileType, null);
		// 获取返回结果并解析返回结果
		ObjectMapper mapper = new ObjectMapper();
		List<Map<String, String>> list = mapper.readValue(jsonString, List.class);
		Map<String, String> map = list.get(0);
		String state = map.get("state");
		if ("0".equals(state)) {
			// 取到base64图片流,然后返给前端
			String imgBas64 = map.get("img");
			BufferedImage bufferedImage = ImgUtil.toImage(imgBas64);
			ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
		}
	}

2、远程接口调用方法代码

	/**
	 * 集上传单个文件与传递参数于一体的方法
	 * 
	 * @param actionURL  上传文件的URL地址包括URL
	 * @param name       文件标识,用于服务器解析(相当于表单名)
	 * @param fileStream 文件流
	 * @param fileName   文件名
	 * @param fileType   文件类型
	 * @param parameters 跟文件一起传输的参数
	 * @return
	 */
	public static String singleFileUploadWithParameters(String actionURL, String name,  InputStream fileStream,
	                                String fileName, String fileType, HashMap<String, String> parameters) {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "----WebKitFormBoundary851PD6JXXxfIPFk9";
		String response = "";
		try {
			URL url = new URL(actionURL);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			// 发送post请求需要下面两行
			connection.setDoInput(true);
			connection.setDoOutput(true);
			// 设置请求参数
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Charset", "UTF-8");
			connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
			// 获取请求内容输出流
			DataOutputStream ds = new DataOutputStream(connection.getOutputStream());
			// 开始写表单格式内容
			// 写参数
			if (parameters != null) {
				Set<String> keys = parameters.keySet();
				for (String key : keys) {
					ds.writeBytes(twoHyphens + boundary + end);
					ds.writeBytes("Content-Disposition: form-data; name=\"");
					ds.write(key.getBytes());
					ds.writeBytes("\"" + end);
					ds.writeBytes(end);
					ds.write(parameters.get(key).getBytes());
					ds.writeBytes(end);
				}
			}
			// 写文件
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; " + "name=\"" + name + "\"; " + "filename=\"");
			// 防止中文乱码
			ds.write(fileName.getBytes());
			ds.writeBytes("\"" + end);
			ds.writeBytes("Content-Type: " + fileType + end);
			ds.writeBytes(end);
			// 根据路径读取文件
			byte[] buffer = new byte[1024];
			int length = -1;
			while ((length = fileStream.read(buffer)) != -1) {
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			fileStream.close();
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			ds.writeBytes(end);
			ds.flush();
			try {
				// 获取URL的响应
				BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
				String s = "";
				String temp = "";
				while ((temp = reader.readLine()) != null) {
					s += temp;
				}
				response = s;
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("No response get!!!");
			}
			ds.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Request failed!");
		}
		return response;
	}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豢龙先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值