springboot中实现上传下载功能

需求

由于项目中需要用户上传文件和下载文件,则后端中需要写相应的接口

实现

下载功能

  • 下载需要传入HttpServletResponse,用于设置header信息
  • 可以同时传入其他信息
@ApiOperation("下载文件")
    @GetMapping("/download/{id}")
    public Result download(@PathVariable Integer id, HttpServletResponse response, @RequestParam("fileName") String fileName) throws IOException {
        TimeInterval timer = DateUtil.timer();

        String uploadFilePath = modulemdService.download(fileName, id);
        File file = new File(uploadFilePath);
        response.reset();
//        response.setContentType("application/octet-stream");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        byte[] readBytes = FileUtil.readBytes(file);//读取文件
        OutputStream os = response.getOutputStream();//获取输出流
        os.write(readBytes);// 输出文件

        return Result.success("花费时间"+timer.interval()+"ms");

    }

上传功能

  • 设置parma参数为file,传入类型为MultipartFile,不能传入requestbody参数
  • new一个File对象,参数为储存在服务器的路径: File fileTempObj = new File(uploadFilePath + "/" + fileName);
  • 使用hutool工具类写入文件,保存在服务器地址:FileUtil.writeBytes(file.getBytes(), fileTempObj);
@PostMapping("/uploadFile")
    public String fileUpload(@RequestParam("file") MultipartFile file) throws JSONException {
        JSONObject result = new JSONObject();
        if (file.isEmpty()) {
            result.append("error", "空文件!");
            return result.toString();
        }
        // 文件名
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传文件名称为:"+fileName+", 后缀名为:"+suffixName);

        File fileTempObj = new File(uploadFilePath + "/" + fileName);
        // 检测目录是否存在
        if (!fileTempObj.getParentFile().exists()) {
            fileTempObj.getParentFile().mkdirs();
        }
        // 使用文件名称检测文件是否已经存在
        if (fileTempObj.exists()) {
            result.put("error", "文件已经存在!");
            return result.toString();
        }

        try {
            // 写入文件:方式1
            // file.transferTo(fileTempObj);
            // 写入文件:方式2
            FileUtil.writeBytes(file.getBytes(), fileTempObj);
        } catch (Exception e) {
            System.out.println("错误信息:"+e.getMessage());
            result.append("error", e.getMessage());
            return result.toString();
        }

        result.append("success", "文件上传成功!");
        return result.toString();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值