SpringBoot+MyBatis对应的文件的上传和下载整合

SpringBoot+MyBatis对应的文件的上传和下载

对应的文件Bean

这里对文章的上传和存入数据库 是进行了修改名字 保证用户看到的数据依然是自己所上传的文件名字 ,对应的后端数据库存入的是加入了UUID进行重新命名。

    private Integer id;
    private String oldFileName;
    private String newFileName;
    private String ext;
    private String path;
    private String size;
    private String type;
    private String isImg;
    private int downCounts;
    private Date uploadTime;
    private int userId;

对应的文件的上传Controller


    //上传文件的处理 并保持文件信息保存到数据库
    @PostMapping("/upload")

    public String upload(MultipartFile aaa, HttpSession session, RedirectAttributes attributes) throws IOException {

        if (aaa.getContentType().equals("application/octet-stream")){
            System.out.println(1);
            attributes.addFlashAttribute("errorMessage","不能上传空文件!");
        }else {
            User user = (User) session.getAttribute("user");

            String oldFileName = aaa.getOriginalFilename();

            String extension = "." + FilenameUtils.getExtension(aaa.getOriginalFilename());
            String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-","").substring(6) + extension;


            long size = aaa.getSize();

            String type = aaa.getContentType();

            //处理根据日期生成目录
            String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files";
            String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String dateDirPath = realPath + "/" + format;

            File dataDir = new File(dateDirPath);
            if (!dataDir.exists()){
                dataDir.mkdirs();
            }

            //处理文件上传
            aaa.transferTo(new File(dataDir,newFileName));

            UserFile userFile = new UserFile();
            userFile.setOldFileName(oldFileName);
            userFile.setNewFileName(newFileName);
            userFile.setExt(extension);
            userFile.setSize(String.valueOf(size));
            userFile.setType(type);
            userFile.setPath("/files/"+format);
            userFile.setUserId(user.getId());

            //将文件存入数据库
            userFileService.SaveFile(userFile);
        }

        return "redirect:/file/showAll";
    }

对应文件下载和查看的controller

此处前端的求情和对应携带参数

在这里插入图片描述

有个小细节就是对应的进行判断 对应传入的openStyle参数 是否为null
以此进行判断是进行下载还是对应的在线查看

判断用户是在线打开还是下载

        openStyle = openStyle == null ? "attachment" : openStyle;
        if ("attachment".equals(openStyle)){
            //更新文件下载次数
            userfile.setDownCounts(userfile.getDownCounts()+1);
            userFileService.update(userfile);
        }
文件下载响应头的设置 
	Content-type  指响应内容的格式
	Content-disposition 知识如何处理响应内容

对应的通过对Header进行设置 对应的content-disposition

两种方式
	Inline 直接在页面显示
	attachment以附件形式下载
@GetMapping("/download")
    public void download(Integer id,String openStyle,HttpServletResponse response) throws IOException {
        UserFile userfile = userFileService.getFilesById(id);
        openStyle = openStyle == null ? "attachment" : openStyle;
        if ("attachment".equals(openStyle)){
            //更新文件下载次数
            userfile.setDownCounts(userfile.getDownCounts()+1);
            userFileService.update(userfile);
        }
        String realpath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userfile.getPath();
        //获取文件输入流
        FileInputStream is = new FileInputStream(new File(realpath, userfile.getNewFileName()));
        //附件下载   URlEncoder.encode进行设置编码  编码格式 UTF-8 避免乱码
        response.setHeader("content-disposition",openStyle+";fileName="+ URLEncoder.encode(userfile.getOldFileName(),"UTF-8"));
        ServletOutputStream os = response.getOutputStream();
        IOUtils.copy(is,os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }

文件删除的contoller

    @GetMapping("/delete")
    public String delete(Integer id) throws FileNotFoundException {
        //根据Id查询信息
        UserFile userFile = userFileService.getFilesById(id);
        //删除文件
        String realpath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userFile.getPath();
        File file = new File(realpath, userFile.getNewFileName());
        if (file.exists()){
            file.delete();//立即删除
        }

        //删除数据库中的纪律
        userFileService.delete(id);
        return "redirect:/file/showAll";
    }

前端页面的展示

在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值