栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot中实现上传下载功能

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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();
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/946939.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号