onlyoffice回调函数controller方式实现

wylc123 5月前 ⋅ 318 阅读

上代码:

//新建报告
	@GetMapping("report/createReport")
	public String CreatReport(HttpServletRequest request,String memo,String reportName,Model model){
		String type = request.getParameter("type");
		String reportCategory = request.getParameter("reportCategory");
		String reportCategoryName = request.getParameter("reportCategoryName");
		String nowTime = DateUtil.getNowDateHm();
		model.addAttribute("type",type);
		model.addAttribute("reportCategory",reportCategory);
		model.addAttribute("reportCategoryName",reportCategoryName);
		model.addAttribute("memo",memo);
		model.addAttribute("reportName",reportName);
		model.addAttribute("nowTime",nowTime);
		return "report/newReport";
	}
	@Value("${xmleditor.onlyoffice_address}")
	private String docserviceApiUrl;
	//onlyoffice新建报告(空白|模板)
	@GetMapping(value = "/report/createReportForOnlyoffice")
	public String createReportForOnlyoffice(HttpServletRequest request, HttpServletResponse response,Model model) {
		String UserCode = SessionHelper.GetLoginUserCode();
		User loginUser = userRepository.getByName(UserCode);
		String fileName = UuidUtil.getUUID()+".docx";
		String reportName= request.getParameter("reportName");
		String HfsKey = request.getParameter("hfsKey");
		String baseUrl = request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+request.getContextPath();
		String getOnlyofficeUrl = baseUrl+"/report/getOfficeFile?filename=";
		OnlyofficeFileModel file = new OnlyofficeFileModel(loginUser,reportName,HfsKey,getOnlyofficeUrl,modelConf.getFileExistUrl(),modelConf.getUploadImgUrl(),"edit");
		String serverPath = request.getScheme() +"://"+ request.getServerName()+":" + request.getServerPort() + request.getContextPath();
		String query = null;
		try {
			query = "?type=track&fileName=" + URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString())
					+"&reportName="+request.getParameter("reportName")
					+"&memo="+request.getParameter("memo")
					+"&doctype="+request.getParameter("type")
					+"&UserCode="+UserCode
					+"&hfsKey="+request.getParameter("hfsKey")
					+"&reportCategory="+request.getParameter("reportCategory");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		file.editorConfig.callbackUrl= serverPath + "/IndexServlet" + query;
		model.addAttribute("file",file);
		model.addAttribute("docserviceApiUrl",docserviceApiUrl);
		model.addAttribute("reportName",reportName);
		return "report/newReport1";
	}
	//查看报告
	@GetMapping(value = "/report/showReportForOnlyoffice")
	public String showReportForOnlyoffice(HttpServletRequest request, HttpServletResponse response,Model model) {
		String UserCode = SessionHelper.GetLoginUserCode();
		User loginUser = userRepository.getByName(UserCode);
		String fileName = request.getParameter("fileName");
		String HfsKey = request.getParameter("hfsKey");
		String baseUrl = request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+request.getContextPath();
		String getOnlyofficeUrl = baseUrl+"/report/getOfficeFile?filename=";
		OnlyofficeFileModel file = new OnlyofficeFileModel(loginUser,fileName,HfsKey,getOnlyofficeUrl,modelConf.getFileExistUrl(),modelConf.getUploadImgUrl(),"view");
		String serverPath = request.getScheme() +"://"+ request.getServerName()+":" + request.getServerPort() + request.getContextPath();
		String query = "?type=show";
		file.editorConfig.callbackUrl= serverPath + "/IndexServlet" + query;
		model.addAttribute("file",file);
		model.addAttribute("reportName",fileName);
		model.addAttribute("docserviceApiUrl",docserviceApiUrl);
		return "report/newReport1";
	}
	//编辑报告
	@GetMapping(value = "/report/editReportForOnlyoffice")
	public String editReportForOnlyoffice(HttpServletRequest request, HttpServletResponse response,Model model) {
		String id = request.getParameter("id");
		String HfsKey = request.getParameter("hfsKey");
		String fileName = request.getParameter("fileName");
		String UserCode = SessionHelper.GetLoginUserCode();
		User loginUser = userRepository.getByName(UserCode);
		String baseUrl = request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+request.getContextPath();
		String getOnlyofficeUrl = baseUrl+"/report/getOfficeFile?filename=";
		OnlyofficeFileModel file = new OnlyofficeFileModel(loginUser,fileName,HfsKey,getOnlyofficeUrl,modelConf.getFileExistUrl(),modelConf.getUploadImgUrl(),"edit");
		String serverPath = request.getScheme() +"://"+ request.getServerName()+":" + request.getServerPort() + request.getContextPath();
		String query = null;
		try {
			query = "?type=edit&fileName=" + URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString())
					+"&doctype="+request.getParameter("type")
					+"&id="+id
					+"&UserCode="+UserCode
					+"&hfsKey="+HfsKey;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		file.editorConfig.callbackUrl= serverPath + "/IndexServlet" + query;
		model.addAttribute("file",file);
		model.addAttribute("reportName",fileName);
		model.addAttribute("docserviceApiUrl",docserviceApiUrl);
		return "report/newReport1";
	}
	@GetMapping("/report/getOfficeFile")
	public void getHfsFile(HttpServletRequest request, HttpServletResponse response) {
		String url = "";
		try {
			String fileName = request.getParameter("filename");
			url = modelConf.getGetImgUrl() + fileName;
			if (StringUtil.isNotBlank(fileName)) {
				HttpClientHelper.getInstance().httpDownloadOfficeFile(url, response);
			} else {
				OutputStream toClient = response.getOutputStream();
				toClient.write("the filename is empty".getBytes());
				toClient.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("文件获取失败,url:{}", url);
		}
	}
	@Autowired
	private FileUploadConfig fileUploadConfig;
	@RequestMapping(value = "/IndexServlet", method = RequestMethod.POST)
	@ResponseBody
	public void IndexServlet(HttpServletResponse response, HttpServletRequest request) throws IOException, ParseException {
		PrintWriter writer = null;
		JSONObject jsonObj=null;
		System.out.println("===saveeditedfile------------");
		try {
			writer = response.getWriter();
			Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
			String body = scanner.hasNext() ? scanner.next() : "";
			jsonObj = (JSONObject) new JSONParser().parse(body);
			System.out.println("===saveeditedfile:" + jsonObj.get("status")) ;
			if ((long) jsonObj.get("status") == 6) {//新建报告(long) jsonObj.get("status") == 2||
				String type = request.getParameter("type");
				if("track".equals(type)){
					String downloadUri = (String) jsonObj.get("url");
					System.out.println("====文档编辑完成,现在开始保存编辑后的文档,其下载地址为:" + downloadUri);
					String fileName = request.getParameter("fileName");
					System.out.println("====下载的文件名:" + fileName);
					String reportName = request.getParameter("reportName");
					String doctype = request.getParameter("doctype");
					String memo = request.getParameter("memo");
					String reportCategory = request.getParameter("reportCategory");
					String UserCode = request.getParameter("UserCode");
					URL url = new URL(downloadUri);
					java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
					InputStream stream = connection.getInputStream();
					File savedFile = new File(fileUploadConfig.getSavePath()+fileName);
					try (FileOutputStream out = new FileOutputStream(savedFile)) {
						int read;
						final byte[] bytes = new byte[1024];
						while ((read = stream.read(bytes)) != -1) {
							out.write(bytes, 0, read);
						}
						out.flush();
					}
					connection.disconnect();
					//上传到hfs
					Map<String, String> map = new HashMap<String, String>();
					map.put("filename", fileName);
					try {
						HttpClientHelper.getInstance().uploadFileImpl(modelConf.getUploadImgUrl(), fileUploadConfig.getSavePath()+fileName, fileName, map);
					} catch (Exception e) {
						e.printStackTrace();
						throw new RuntimeException("上传文件失败");
					}
					//保存到表中 报告
					if("report".equals(doctype)){
						/*添加报告*/
						Report report = new Report();
						int flag_add = 0;
						//report.setReportContentID(bookId);
						report.setReportXML("");//预留字段
						report.setReportCode("");//预留字段
						report.setReportName(reportName);
						report.setReportCategoryID(Integer.parseInt(reportCategory));
						report.setStatus(1);
						report.setMemo(memo);
						report.setCreateUser(UserCode);
						Date day=new Date();
						report.setCreateTime(day);
						report.setHfsKey(fileName.substring(0,fileName.length()-5));
						flag_add = reportService.addReportOnlyoffice(report);
					}else if("reportTemplet".equals(doctype)){
						/*添加报告模板*/
						ReportTemplet reportT = new ReportTemplet();
						int flag_add = 0;
						//reportT.setReportContentID(bookId);
						reportT.setReportTempletXML("");//预留字段
						reportT.setReportTempletCode("");//预留字段
						reportT.setReportTempletName(reportName);
						reportT.setReportCategoryID(Integer.parseInt(reportCategory));
						reportT.setStatus(1);
						reportT.setMemo(memo);
						reportT.setCreateUser(UserCode);
						reportT.setHfsKey(fileName.substring(0,fileName.length()-5));
						Date day=new Date();
						reportT.setCreateTime(day);
						flag_add = reportTempletService.addReportTempletOnlyOffice(reportT);
					}
				}else if("show".equals(type)){//查看报告
					System.out.println("====只查看不保存:");
				}else if("edit".equals(type)){//修改报告
					String downloadUri = (String) jsonObj.get("url");
					System.out.println("====文档编辑完成,现在开始保存编辑后的文档,其下载地址为:" + downloadUri);
					String doctype = request.getParameter("doctype");
					String UserCode = request.getParameter("UserCode");
					String HfsKey = request.getParameter("hfsKey");
					String id = request.getParameter("id");
					String fileName = HfsKey+".docx";
					URL url = new URL(downloadUri);
					java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
					InputStream stream = connection.getInputStream();
					File savedFile = new File(fileUploadConfig.getSavePath()+fileName);
					try (FileOutputStream out = new FileOutputStream(savedFile)) {
						int read;
						final byte[] bytes = new byte[1024];
						while ((read = stream.read(bytes)) != -1) {
							out.write(bytes, 0, read);
						}
						out.flush();
					}
					connection.disconnect();
					//上传到hfs
					Map<String, String> map = new HashMap<String, String>();
					map.put("filename", fileName);
					try {
						HttpClientHelper.getInstance().uploadFileImpl(modelConf.getUploadImgUrl(), fileUploadConfig.getSavePath()+fileName, fileName, map);
					} catch (Exception e) {
						e.printStackTrace();
						throw new RuntimeException("上传文件失败");
					}
					//保存到表中 报告
					if("report".equals(doctype)){
						/*添加报告*/
						Report report = reportService.getByID(Integer.valueOf(id));
						int flag_up = 0;
						report.setModifyUser(UserCode);
						Date day=new Date();
						report.setModifyTime(day);
						report.setStatus(1);//修改后需要重新发布
						flag_up = reportService.updateReportInfo(report);
					}else if("reportTemplet".equals(doctype)){
						/*添加报告模板*/
						ReportTemplet reportT = reportTempletService.getByID(Integer.valueOf(id));
						int flag_up = 0;
						reportT.setModifyUser(UserCode);
						Date day=new Date();
						reportT.setModifyTime(day);
						reportT.setStatus(1);//修改后需要重新发布
						flag_up = reportTempletService.updateReportTempletInfo(reportT);
					}
				}

			}
		}catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if((long) jsonObj.get("status") == 3||(long) jsonObj.get("status") == 7) {
			System.out.println("====保存失败:");
			writer.write("{\"error\":1}");
		}else {
			writer.write("{\"error\":" + "0" + "}");
		}
	}
 

如有其他疑问可加入Q群,共同探讨:

onlyoffice交流群


相关文章推荐

全部评论: 0

    我有话说: