关于RestFul接口的文件导入导出的实现

如果一个接口的请求参数或者相应接口的数据内容过大,需要以json文件的形式来进行交互,可以通过以下方式进行编码实现
导入json类型的文件

/**
     * 流程导入json数据接口
     */
    @PostMapping("/deployProd/import")
    @Timed
    @ApiOperation(value="流程导入json数据接口", notes="流程导入json数据接口")
    public HttpEntity<DeployProdF07RespM01> importProcess(HttpServletRequest request) throws Exception {
    	// 从url?processClassificationId=xxx 中获取其他的参数信息
        String processClassificationId = (String)request.getParameter("processClassificationId");
        MultipartHttpServletRequest multipartHttpServletRequest = null;
        try {
            multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        } catch (Exception e) {
            throw new BizLogicException(new I18nMessage("CommonObjectImportUploadMSG02"));
        }
        // 传的文件
        MultipartFile file = multipartHttpServletRequest.getFile("file");
        DeployProdF07ReqtM01 deployProdF07ReqtM01 = new DeployProdF07ReqtM01();
        if (file != null) {
        	String processStr = new String(file.getBytes(), "UTF-8");
        	deployProdF07ReqtM01 = objectMapper.convertValue(objectMapper.readTree(processStr ), DeployProdF07ReqtM01.class);
        	deployProdF07ReqtM01.setProcessClassificationId(processClassificationId);
        }
        DeployProdF07RespM01 result = deployProdF07BLogic.execute(deployProdF07ReqtM01);
        return new ResponseEntity<DeployProdF07RespM01>(result, HttpStatus.OK);
    }

导出json类型的文件

    /**
     * 流程导出json数据接口
     */
    @PostMapping("/deployProd/export")
    @Timed
    @ApiOperation(value="流程导出json数据接口", notes="流程导出json数据接口")
    public void exportProcess(@ApiParam @RequestBody @Validated DeployProdF06ReqtM01 deployProdF06ReqtM01, HttpServletResponse response) throws Exception {
        log.info("流程导出json数据接口: {}", deployProdF06ReqtM01);
        DeployProdF06RespM01 result = deployProdF06BLogic.execute(deployProdF06ReqtM01);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            byte[] data = objectMapper.writeValueAsBytes(result);
            response.reset();
            response.setHeader("Content-Disposition","attachment;fileName=" + "processData.json");
            response.addHeader("Content-Length", data.length + "");
            response.setContentType("application/octet-stream;charset=UTF-8");
            IOUtils.write(data, out);
        } catch (Exception e) {
            log.error(MessageFormat.format("下载文件出现的异常:", e.getMessage()), e);
        } finally {
            out.flush();
            out.close();
        }
    }

你可能感兴趣的:(JAVA)