大概实现结果
实现Jquery ajax代码
<script>
$("#btn1").click(function () {
//创建FormData对象
var formData = new FormData();
formData.append("file", $("#file1")[0].files[0]);
$.ajax({
url: "./Servlet",
method: "POST",
data: formData,
contentType: false,
processData: false,
cache: false,
success: function (data) {
var info_main = JSON.parse(data); //将json数据反序列化为JavaScript对象
console.log(info_main);
var main1 = info_main.words_result;
console.log(main1);
var main2 = main1[0];
var color = main2.color;
var number = main2.number;
var probability = main2.probability;
console.log(color);
$("#result_info_color").html(color);
$("#result_info_number").html(number);
},
error: function (jqXHR) {
console.log(JSON.stringify(jqXHR));
}
})
});
</script>
servlet代码
public class Servlet extends HttpServlet {
public static final String APP_ID = "17863411";
public static final String API_KEY = "qq64CnbCCtpmxwq7B3zHsgTH";
public static final String SECRET_KEY = "n1IB7x4I2ijPa1DAvYOQt3EICzmDIcYR";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
//获取文件、图片的方式
// 获取二进制文件
Part headimg1 = request.getPart("file");
// 获取文件名称
String header = headimg1.getHeader("content-disposition");
// System.out.println(header);
String filename=getFileName(header);
System.out.println(filename);
// 获取upload目录具体位置
String realPath = request.getServletContext().getRealPath("upload");
// 将文件写入目录
System.out.println(realPath+'/'+filename);
String filePath=realPath+"/"+filename;
System.out.println(filePath);
headimg1.write(filePath);
AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
// 车牌识别
HashMap<String, String> options = new HashMap<String, String>();
options.put("multi_detect", "true");
// 参数为本地路径
String image = filePath;
JSONObject res = client.plateLicense(image, options);
String Detect_Reslut= JSON.toJSONString(res);
response.getWriter().println(res.toString(2));
System.out.println(res.toString(2));
}
获取文件名函数:
String getFileName(String head){
String fileName = null;
String[] split = head.split(";");
String[] split1 = split[2].split("=");
fileName=split1[1].substring(1,split1[1].length()-1);
return fileName;
}