File图片文件上传到本地服务器tomcat保存到数据库并且展示

保存tomcat路径为E:\apache-tomcat-7.0.72\webapps\sxserver\tempFile\idcard\2018\12\20\1545030451229.png

保存数据库路径为\sxserver\tempFile\idcard\2018/12/20\1545030451229.png

/**
	 * 百度ocr身份证营业执照识别
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	//TODO
	public String baiduOcr() {
		// 初始化一个AipOcr
		AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
		// 可选:设置网络连接参数
		client.setConnectionTimeoutInMillis(2000);
		client.setSocketTimeoutInMillis(60000);
		// 传入可选参数调用接口
		HashMap options = new HashMap();
		options.put("detect_direction", "true");
		options.put("detect_risk", "false");
		// front - 身份证含照片的一面 back - 身份证带国徽的一面
		String idCardSide = "front";
		// 保存图片到本地服务器路径
		//String filetype = request.getParameter("filetype");
		String dirPath = request.getSession().getServletContext()
				.getRealPath("/");
		File dirFile = new File(dirPath);

		String datedir = DateTools.getStringFromDate(new Date(),"yyyy/MM/dd");

		String filepathdir = "tempFile"+ File.separator+ filetype + File.separator + datedir+ File.separator;

		File serverFiledir = new File(dirFile.getParent() + File.separator+ "sxserver" + File.separator+ filepathdir);
		if(!serverFiledir.exists()){
			serverFiledir.mkdirs();
		}
		String fileName=null;
			fileName = new Date().getTime()+ (int) (Math.random() * 10000)+ fileFileName.substring(fileFileName.lastIndexOf("."));
		/*}*/
		File targetFile = new File(serverFiledir, fileName);
		//将图片写入到服务器
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(file.getPath());
			fos = new FileOutputStream(targetFile.getPath());
	
			byte[] buffer = new byte[1024];
			int len = 0;
	
			while ((len = fis.read(buffer)) != -1) {
			fos.write(buffer,0, len);
			fos.flush();
		}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		JSONObject json=new JSONObject();
		if(filetype.equals("idcard")) {
			json = client.idcard(targetFile.getPath(), idCardSide, options);
		}else {
			json =client.businessLicense(targetFile.getPath(), options);
		}
		System.out.println(json.toString());
		
		String src = File.separator + "sxserver"+ File.separator + filepathdir + fileName;
		json.put("imgSrc", src);
		success = json.toString();
		return "success";
	}
企业法人身份证

jsp页面展示图片

var image="http://127.0.0.1:8080/\sxserver\tempFile\idcard\2018/12/20\1545030451229.png";
$("#showimg2").get(0).src=image;

详情请参考-->不用form表单上传图片两种方式FormData和ajaxFileUpload

你可能感兴趣的:(JAVA基础)