Java下载文件的几种方式含本地文件下载

1.以流的方式下载.

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

            // 以流的形式下载文件。
            InputStream 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();
        }
        return response;
    }

2.下载本地文件

public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
        // 下载本地文件
        String fileName = "Operator.doc".toString(); // 文件的默认保存名
        // 读到流中
        InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3.下载网络文件

public void downloadNet(HttpServletResponse response) throws MalformedURLException {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;

        URL url = new URL("windine.blogdriver.com/logo.gif");

        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            //设置超时时间
            conn.setConnectTimeout(3 * 1000);
            // 防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;         Windows NT; DigExt)");
            // 下载本地的文件
            FileOutputStream fs = new FileOutputStream("c:/abc.gif");
            /** web下载放开此注释
         // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new             String(filename.getBytes()));
            response.setContentType("application/octet-stream");
**/
            byte[] buffer = new byte[1204];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                //bytesum += byteread;
                //System.out.println(bytesum);
                fs.write(buffer, 0, byteread);
// web下载放开此注释
//response.getOutputStream().write(buffer, 0, byteread);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

4.支持在线打开的方式

public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;

        response.reset(); // 非常重要
        if (isOnLine) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.close();
    }

5.springMVC文件下载更方便

@RequestMapping(value="/download",method=RequestMethod.GET) //匹配的是href中的download请求
    public ResponseEntity<byte[]> download(HttpServletRequest request,@RequestParam("filename") String filename,
            Model model) throws IOException{
        
        String downloadFilePath="D:\\userUploadFile\\Files";//从我们的上传文件夹中去取
        
        File file = new File(downloadFilePath+File.separator+filename);//新建一个文件
        
        HttpHeaders headers = new HttpHeaders();//http头信息
        
        String downloadFileName = new String(filename.getBytes("UTF-8"),"iso-8859-1");//设置编码
        
        headers.setContentDispositionFormData("attachment", downloadFileName);
        
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        
        //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
        
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
        
    }

欢迎关注我的公众号:(づ ̄3 ̄)づ╭❤~

  • 4
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
Vue是一种流行的JavaScript框架,用于构建用户界面。而Java是一种广泛使用的编程语言,可以用于开发后端服务器和处理业务逻辑。在Vue中,我们可以通过发送HTTP请求来实现文件下载。 要在Vue中实现文件下载,我们可以使用axios库来发送HTTP请求。首先,我们需要安装axios库并在代码中导入。然后,我们可以使用axios的get方法来发送GET请求获取要下载文件。 在组件的方法中,我们可以使用axios来发送GET请求,并将服务器返回的文件存储到本地。我们可以为这个请求指定一个URL,该URL由后端服务器提供,向后端服务器请求一个特定的文件。当我们收到服务器的响应时,我们可以将接收到的文件保存到本地。可以使用Blob对象和createObjectURL方法将服务器响应转换为可下载的URL。 接下来,我们可以创建一个用于触发文件下载的按钮或链接,并将上述方法与点击事件绑定。当用户点击按钮或链接时,该方法将被调用,并触发下载。 总之,在Vue中实现文件下载的过程可以分为以下几个步骤: 1. 安装并导入axios库。 2. 使用axios的get方法发送GET请求获取要下载文件。 3. 将接收到的文件保存到本地。 4. 创建一个触发下载的按钮或链接,并将方法与点击事件绑定。 这样,我们就可以在Vue中实现文件下载功能。希望以上解答对您有帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值