Spring boot 2.0 web plus file upload and download

Record the file upload and download of spring webplus.

There is no HTTP servlet request and HTTP servlet response based on servlet container before using webplus. Instead, there are org.springframework.http.server.reactive.ServerHttpRequest and org.springframework.http.server.reactive.ServerHttpResponse.

Application scenario:

1. File upload: the front end uploads the file, the back end parses the file content and saves it to the database;

2. File export: query data and export to file

File upload

@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);
}

Before and after reading the contents of the file, the logic is omitted:

@Override
public Map<String, Object> importRouteConfig(FilePart file) {
	Map<String, Object> objMap = new HashMap<String, Object>(GatewayNumberConstant.TWO);
	try{
		......
		// Read file contents
		String strFileInfo = ImportExportUtil.readJsonFile(file);
		......
		objMap.put("state", Boolean.valueOf(true));
	} catch (Exception e) {
		LOG.error("Import failed: unexpected exception.", e);
		objMap.put("message", "Unexpected exception, please contact the maintenance personnel for handling.");
		objMap.put("state", Boolean.valueOf(false));
	}
	return objMap;
}

Read file contents:

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());
		});
		//Get request body
		strFileInfo = bodyRef.get();
		if(null==strFileInfo){
			LOG.error("Import failed: file is empty");
			throw new RuntimeException("Import failed: file is empty");
		}else if(strFileInfo.length()>MAX_DATA_SIZE){
			LOG.error("Import failed: file size cannot exceed 4 M");
			throw new RuntimeException("Import failed: file size cannot exceed 4 M");
		}
	}
	return strFileInfo;
}

Here strFileInfo is to get the file content information.

File export

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

Export tool class

/**
	* export file
	* 
	* @param fileName Filename, for example: GatewayRouteConfig
	* @param lstConfig Pass in the list to write to
	* @param response response
	*/
public static Mono<Void> exportJsonFile(String fileName, List lstConfig, ServerHttpResponse response) {
	if(null == lstConfig || lstConfig.isEmpty()) {
		LOG.error("The content of the export file is empty.");
		throw new RuntimeException("The content of the export file is empty.");
	}

	// Definition file name for example: 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("Failed to export file:", e);
	} catch (Exception e) {
		LOG.error("Failed to export file:", e);
	} 
	return null;
}

It should be noted that the coding format of the exported file and the imported file should be consistent, otherwise, the Chinese code will be garbled.

Keywords: Programming JSON Spring Database

Added by Kasuke_Akira on Mon, 06 Jan 2020 15:20:45 +0200