javaweb中分页和文件读写功能

1、分页原理

在这里插入图片描述

2、删除

     /**
     * 查询指定id的记录
     * @param id id
     * @return Result<Category>
      * restful格式:delete localhost:8080/api/v6/admin/category/1001
      * 传统格式:delete localhost:8080/api/v6/admin/category? id=1001
     */

    @GetMapping()
    @Operation(summary =  "查询指定id的记录" )
    public Result<Category> getById(Long id) {
        log.info("id = {}",id);

        //调用服务层Mybatis-plus自动提供的getById方法
        Category category= categoryService.getById(id);

        return Result.success(category);
    }

3、文件读写流 stream

在这里插入图片描述

    @Operation(summary = "从配置项指定的文件夹中,下载指定的文件")
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        FileInputStream fis =null;
        ServletOutputStream os=null;
        try {
            fis= new FileInputStream(basePath + name);
            os = response.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }

        } catch (Exception e) {
            log.error(e.getMessage());
            //throw new RuntimeException(e);
        } finally {
            if(fis != null) {
                fis.close();
            }
            if(os != null){
                os.close();
            }
        }
    }

4、文件上传和下载

package cn.zz.yunhe.study.shequgouv6.controller.admin;

import cn.zz.yunhe.study.shequgouv6.common.Result;
import cn.zz.yunhe.study.shequgouv6.properties.FileUpDownPath;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传下载模块
 * @version 0.01
 * @Author yuch
 * @Date 2023-08-04 09:41
 **/
@Slf4j
@Tag(name = "文件上传、下载的公共模块")
@RestController
@RequestMapping("/api/v6/admin/common")
public class CommonController {
    //利用配置类,获取配置文件中的配置
    @Autowired
    private FileUpDownPath fileUpDownPath;
    //直接获取配置文件中的配置,并存放到变量中
    @Value("${shequgou.img.path}")
    private String basePath;

    /**
     * 文件上传到配置项所指定的文件夹中,并文件名UUID格式化
     * @param file  file是上传到服务器上的临时文件,我们在断点调试的时候可以看到,
     *   但是执行完整个方法之后就消失了
     * @return Result<String>
     */
    @Operation(summary = "文件上传到配置项所指定的文件夹中,并文件名UUID格式化")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        log.info("上传文件文件:{},", file.toString());
        log.info("从自定义配置属性中毒配置路径:{}",fileUpDownPath.getPath());

        //1.判断一下配置属性中指定的目录是否存在,不存在则创建
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        //2.利用原文件名的扩展名和UUID,生成新的文件名
        //获取一下传入的原文件名
        String originalFilename = file.getOriginalFilename();
        //我们只需要获取一下格式后缀,取子串,起始点为最后一个.
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //为了防止出现重复的文件名,我们需要使用UUID
        String fileName = UUID.randomUUID() + suffix;

        try {
            //3.把原文件转移到指定文件夹下,并改成新的文件名
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //4.将文件名返回给前端,便于后期的开发
        return Result.success(fileName);
    }

    /**
     * 从配置项指定的文件夹中,下载指定的文件
     * @param name 文件名
     * @param response response
     * @throws IOException   关闭文件资源时的异常抛出
     */
    @Operation(summary = "从配置项指定的文件夹中,下载指定的文件")
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        FileInputStream fis =null;
        ServletOutputStream os=null;
        try {
            fis= new FileInputStream(basePath + name);
            os = response.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }

        } catch (Exception e) {
            log.error(e.getMessage());
            //throw new RuntimeException(e);
        } finally {
            if(fis != null) {
                fis.close();
            }
            if(os != null){
                os.close();
            }
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值