Springboot后台 uniapp前端 实现文件的下载与上传〖文件下载篇〗

Springboot实现文件的下载与上传

一.Springboot为后台实现下载文件

  • 大概思路:从前端获取一个要下载的文件名后(包含后缀名称),HttpServletResponse返回一个流文件
  • 可能存在的问题:uniapp为前端的saveFile()方法不支持h5
  • 存在跨域问题
  • 文件大小的限制

二.上代码

 /**
     * 下载文件
     * @param name
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/download/{fileName}")
    public CommonReturnType downloadFile(@PathVariable("fileName") String name, HttpServletResponse response) throws UnsupportedEncodingException {

        String filePath="E:/fileSource";  //文件的根目录
        File file=new File(filePath+"/"+name); //处理用的文件类,用于操作这个目录下的文件
        if (file.exists()){ //判断是否存在此文件
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(name,"UTF-8"));  //为了下载的东西不乱码而设置前三个格式

            byte[] buffer=new byte[1024]; //每次读取的最大字节数
            FileInputStream fis=null;  //建立缓冲输入字节流
            BufferedInputStream bis=null; 
            OutputStream os=null;
            try {
                os=response.getOutputStream();//向response缓冲区中写入字节
                fis=new FileInputStream(file);
                bis=new BufferedInputStream(fis);
                int i=bis.read(buffer);  //读取缓存,若读不到返回-1
                while(i!=-1){
                    os.write(buffer);
                    i=bis.read(buffer);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println("----------file download---" + name);
            try{
                bis.close();  //关闭流
                fis.close();
            }catch (IOException e){
                e.printStackTrace();
            }
            return null;
        }
        return null;
    }

三.前端

<a href="http://127.0.0.1:8093/file/download/kaikai.png">下载图片</a>
  • 这里我直接指定了download下的路径参数为kaikai.png是一张图片
  • 通过连接的形式下载东西

在这里插入图片描述
通过点击会出现下载选项,选择把保存就能保存到本地!

四.处理问题

跨域问题处理: 由于我用的是springboot后台,直接在一个controller层的类名上加一个 @CrossOrigin注解,即可解决跨域问题

前端h5可以通过更简洁的方法处理下载,我用的链接太傻了,会uniapp的大佬教我解决一下~

制作不易,py请标注~~

发布了69 篇原创文章 · 获赞 54 · 访问量 9580

猜你喜欢

转载自blog.csdn.net/kingtok/article/details/102998124