自学内容网 自学内容网

Springboot 文件上传下载相关问题

关于Springboot 文件上传下载问题解决方案

我觉得最好的办法就是将这些代码先写一遍出来,然后再琢磨一下是什么原理,虽然代码有些繁琐

注意事项

在这里插入图片描述

我们可以注意到,这个文件上传 的 enctype 格式必须设置成 “multipart / from-data” 哦。

文件上传

先把需求罗列出来
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

代码如下:

    @PostMapping("/addFile")
    public String addFile(MultipartFile file,HttpSession request) throws IOException {
        // 获得旧文件名称
        String originalName = file.getOriginalFilename();
        // 获取文件的后缀
        String ext = "." + FilenameUtils.getExtension(originalName);
        // 获得新文件名称
        String newName = new SimpleDateFormat("yyyyMMdd").format(new Date()) + UUID.randomUUID().toString().replace("-","")+ext;
        // 获得储存的路径
        String path = ResourceUtils.getURL("classpath:").getPath()+"static/test/";
        String path1 = URLDecoder.decode(path, "utf-8");
        // 获取新的文件夹,要是不存在,就默认创建
        java.io.File files = new java.io.File(path1 + newName);
        if(!files.exists()) {
            boolean b = files.mkdirs();
        };
        // 获取文件的大小
        String size = file.getSize() + "kb";
        // 上传文件
        file.transferTo(files);
        
        File f = new File();
        f.setId(UUID.randomUUID().toString());
        f.setOldName(originalName);
        f.setNewName(newName);
        f.setExt(ext);
        f.setPath(path1);
        f.setSize(size);
        String houZhui = FilenameUtils.getExtension(originalName);
        if(houZhui.equals("png") || houZhui.equals("img") || houZhui.equals("jpg")){
            f.setStyle("是");
        }else{
            f.setStyle("否");
        }
        f.setImg(path1+newName);
        f.setDownCounts("0");
        f.setDownTime(new SimpleDateFormat("yyMMddHHmmss").format(new Date()));
        com.xiao.entity.User user = (com.xiao.entity.User) request.getAttribute("user");
        f.setUid(user.getId());
        filempl.addFiles(f);
        return "redirect:/selectFiles";
    }

文件下载

在这里插入图片描述

代码如下:

    @GetMapping("/download")
    public void downloadFile(@Param("id")String id , HttpServletResponse response) throws IOException {

        File file = filempl.queryFile(id);

        // 获取要下载文件的 url
        String paths = ResourceUtils.getURL("classpath:").getPath()+"/static/test";

        //获取文件输入流
        FileInputStream is = new FileInputStream(new java.io.File(paths,file.getNewName()));

        // 附件下载
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(file.getOldName(),"utf8"));

        // 获取输出响应流
        ServletOutputStream os = response.getOutputStream();

        IOUtils.copy(is,os);

        // 关闭流
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);

//        问题二:不需要返回,因为是下载,不存在页面转跳问题
//        return "forward:/selectFiles";

文件删除

在这里插入图片描述

代码如下:

    @GetMapping("/delFile")
    public String delFile(@Param("id")String id) throws IOException {
        // 根据id查找到当前的User对象
        File file = filempl.queryFile(id);

        String id1 =file.getNewName();
        // 如果文件存在,则删除文件
        boolean del = Files.deleteIfExists(Paths.get("D:\\javaPorject\\thirdTest\\target\\classes\\static\\test\\"+id1));

        // mapper 删除文件
        filempl.delFiles(id);
        return "forward:/selectFiles";
    }

文件在线打开

在这里插入图片描述

仅仅多了一个 “ inline; ”,就变成了在线打开。

在写练习的时候,发现了一些小小的问题,已经在 上述代码中体现。

① 代码路径碰到中文的时候,会有乱码,需要转换(内容中已解决)

② 在下载文件的时候,无需转跳问题(内容中已解决)


原文地址:https://blog.csdn.net/quokka56/article/details/142100831

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!