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();
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)) {
String imgBas64 = map.get("img");
BufferedImage bufferedImage = ImgUtil.toImage(imgBas64);
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}
}
2、远程接口调用方法代码
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();
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 {
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;
}