02vue+axios+form实现文件下载(附Java实现代码)

参考文章

form实现文件下载

1.0前端实现思路

用一个from接收后台返回的文件流。form用display为none隐藏;其中form构造action属性,属性值为后台文件下载的参数。同样可以用display为none的input插入form中,input可以携带参数,后台可以用@requestParam接收。
前端具体代码如下:





    
    
    
    Document



    

02.java代码实现

后端Java代码实现首先将文件读入到数组buffer中,然后用response获取输出流,输出流将buffer写出即可。

@GetMapping("/download")
    public void download(@RequestParam("path") String path, HttpServletResponse response) {
        System.out.println(path);
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis;
            fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

你可能感兴趣的:(02vue+axios+form实现文件下载(附Java实现代码))