springboot2.0 webflux文件上传与下载

假如想象 提交于 2020-01-07 03:54:47

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

记录一下spring webflux的文件上传和下载。

使用webflux就没有之前基于servlet容器的HttpServletRequest及HttpServletReponse了,取而代之的是org.springframework.http.server.reactive.ServerHttpRequest以及org.springframework.http.server.reactive.ServerHttpResponse。

应用场景:

    1.文件上传:前端上传文件,后台解析文件内容并保存到数据库;

    2.文件导出:查询数据,并导出到文件

文件上传

@RequestMapping(value = "/console/routes/import", method = RequestMethod.POST,consumes = MediaType.MULTIPART_FORM_DATA_VALUE )
@ResponseBody
public Map<String,Object> importRouteConfig(@RequestPart(value="file") FilePart file)throws Exception {
	return routeConfigService.importRouteConfig(file);
}

读取文件内容前后逻辑省略:

@Override
public Map<String, Object> importRouteConfig(FilePart file) {
	Map<String, Object> objMap = new HashMap<String, Object>(GatewayNumberConstant.TWO);
	try{
		......
		// 读取文件内容
		String strFileInfo = ImportExportUtil.readJsonFile(file);
		......
		objMap.put("state", Boolean.valueOf(true));
	} catch (Exception e) {
		LOG.error("导入失败:不可预期的异常。", e);
		objMap.put("message", "不可预期的异常,请联系维护人员处理。");
		objMap.put("state", Boolean.valueOf(false));
	}
	return objMap;
}

读取文件内容:

public static String readJsonFile(FilePart file) throws IOException {
	String strFileInfo = null;
	if(validateJsonFile(file)) {
		AtomicReference<String> bodyRef = new AtomicReference<>();
		file.content().subscribe(buffer->{
			CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
			DataBufferUtils.release(buffer);
			bodyRef.set(charBuffer.toString());
		});
		//获取request body
		strFileInfo = bodyRef.get();
		if(null==strFileInfo){
			LOG.error("导入失败:文件为空");
			throw new RuntimeException("导入失败:文件为空");
		}else if(strFileInfo.length()>MAX_DATA_SIZE){
			LOG.error("导入失败:文件大小不能超过4M");
			throw new RuntimeException("导入失败:文件大小不能超过4M");
		}
	}
	return strFileInfo;
}

这里的strFileInfo即为获取到文件内容信息。

文件导出

@RequestMapping(value = "/console/routes/export", method = RequestMethod.GET)
@ResponseBody
public Mono<Void> exportRouteConfig(@RequestParam("ids") String[] ids, ServerHttpResponse response) {
	return routeConfigService.exportRouteConfig(ids, response);
}

导出工具类

/**
	* 导出文件
	* 
	* @param fileName 文件名,例如:GatewayRouteConfig
	* @param lstConfig 传入要写入文件的list
	* @param response 响应
	*/
public static Mono<Void> exportJsonFile(String fileName, List lstConfig, ServerHttpResponse response) {
	if(null == lstConfig || lstConfig.isEmpty()) {
		LOG.error("导出文件内容为空。");
		throw new RuntimeException("导出文件内容为空。");
	}

	// 定义文件名称 例如:GatewayRouteConfig-2019-01-07.json
	String strFileName = fileName + "-" + timestampConvertString(
			new Timestamp(System.currentTimeMillis()), "yyyy-MM-dd") + ".json";
	try {
		response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
		response.getHeaders().add("Content-Disposition", "attachment;filename=" 
					+ new String(strFileName.getBytes(DEFAULT_CHARSET_UTF_8), StandardCharsets.ISO_8859_1));

		Gson objGson = new Gson();
		String strRouteConfig = objGson.toJson(lstConfig);
		Flux<DataBuffer> flux = export(strRouteConfig);
		return response.writeWith(flux);

	} catch (UnsupportedEncodingException e) {
		LOG.error("导出文件失败:", e);
	} catch (Exception e) {
		LOG.error("导出文件失败:", e);
	} 
	return null;
}

需要注意的是,导出文件与导入文件的编码格式要保持一致,否则会导致中文乱码。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!