JavaWeb 文件上传/下载

文件上传/下载

文件上传

  1. 上传类型设置为"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("上传失败!");
            }
        }
    

文件下载

  1. 使用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));
    }
    
  2. 使用二进制流写入相应输出流下载
    @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);
                }
            }
        }
    }
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值