文件上传
- 上传类型设置为"multipart/form-data"
<form method="POST" action="/upload" enctype="multipart/form-data"> <input type="file" name="file" /> </form>
@PostMapping("/temp") public Result temp(@RequestParam("file") MultipartFile file){ try { String temp = PropertiesFactory.getPropertiesBean().getHdfsRootPath() + "temp/upload_" + ToolUtil.getRandomString(32) + "." + ToolUtil.getFileSuffix(file.getOriginalFilename()); Map<String,String> tempPath = new HashMap<>(); tempPath.put("tempPath",temp); Supplier<HDFSUtil> supplier = HDFSUtil :: new; HDFSUtil hdfsUtil = supplier.get(); hdfsUtil.uploadStreamToHDFS(file.getInputStream(),temp); Map<String,Object> map = new HashMap<>(); map.put(GlobalConst.JSON_DATA,tempPath); return Result.ok(map); }catch (Exception e){ throw new ServiceException("上传失败!"); } }
文件下载
- 使用springweb框架 ResponseEntity进行文件下载
@GetMapping("/down/{id}") public ResponseEntity<InputStreamResource> down(@PathVariable Integer id) { String data = gaiTableService.down(id); ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getBytes()); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition",String.format("attachment; filename=\"%s\".csv", DateUtils.getTimeStampStr(new Date()))); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return ResponseEntity.ok().headers(headers).body(new InputStreamResource(inputStream)); }
- 使用二进制流写入相应输出流下载
@GetMapping("/down/{id}") public void down(@PathVariable Integer id, HttpServletResponse response) { InputStream in = null; OutputStream out = null; try { //获取业务数据 String data = gaiTableService.downData(id); GaiTable gaiTable = gaiTableService.findById(id); List<String> fileName = BaseJSONUtil.jsonToBean(gaiTable.getFilename(), List.class); String path = PropertiesFactory.getPropertiesBean().getHdfsRootPath() + gaiTable.getPath().substring(1) + fileName.get(0); /** 下载处理*/ response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\".csv", DateUtils.getTimeStampStr(new Date()))); out = response.getOutputStream(); out.write(data.getBytes()); out.write(GlobalConst.NEWLINE.getBytes()); /* 拼接其他数据输出到同一个文件中**/ byte[] bytes = new byte[1024]; in = HdfsUtilFactory.getHdfsUtil().getHdfsInputStream(path); int len = 0; while ((len = in.read(bytes)) > 0) { out.write(bytes, 0, len); } } catch (Exception e) { logger.error("数据下载失败异常!", e); throw new ServiceException("下载失败!", e); } finally { if (in != null) { try { if (!ToolUtil.isEmpty(in)){ in.close(); } if (!ToolUtil.isEmpty(out)){ out.close(); } } catch (Exception e) { logger.error("IO 关闭异常!", e); } } } }