java实现文件下载的几种情况

需求:实现一个具有文件下载功能的网页,主要下载压缩包和图片

两种实现方法:

一:通过超链接实现下载

在HTML网页中,通过超链接链接到要下载的文件的地址
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <meta charset="UTF-8">  
  5. <title>Insert title here</title>  
  6. </head>  
  7. <body>  
  8. <h1>通过链接下载文件</h1>  
  9. <a href="/day06/download/cors.zip">压缩包</a>  
  10. <a href="/day06/download/1.png">图片</a>  
  11. </body>  
  12. </html>  

其中day06/download是文档路径,本实例的程序结构如下:

程序运行后,可以通过单击需要下载文档实现下载

但是这里会出现一个问题,就是单击下载压缩包的时候会弹出下载页面,但是下载图片的时候浏览器就直接打开了图片,没有下载。

    这是因为通过超链接下载文件时,如果浏览器可以识别该文件格式,浏览器就会直接打开。只有浏览器不能识别该文件格式的时候,才会实现下载。因此利用第二种方法实现下载功能。


二:通过Servlet程序实现下载

    通过Servlet下载文件的原理是通过servlet读取目标程序,将资源返回客户端。
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <meta charset="UTF-8">  
  5. <title>Insert title here</title>  
  6. </head>  
  7. <body>  
  8. <h1>通过链接下载文件</h1>  
  9. <a href="/day06/download/cors.zip">压缩包</a>  
  10. <a href="/day06/download/1.png">图片</a>  
  11. <h1>通过servlet程序下载文件</h1>  
  12. <a href="/day06/ServletDownload?filename=cors.zip">压缩包</a>  
  13. <a href="/day06/ServletDownload?filename=1.png">图片</a>  
  14. </body>  
  15. </html>  

其中,/day06/ServletDownload 是servlet程序的映射路径
然后新建一个servlet,名称为ServletDownload,URL映射为/ServletDownload

添加代码如下:
  1. package com.lsgjzhuwei.servlet.response;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8.   
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.annotation.WebServlet;  
  11. import javax.servlet.http.HttpServlet;  
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14.   
  15. /** 
  16.  * Servlet implementation class ServletDownload 
  17.  */  
  18. @WebServlet(asyncSupported = true, urlPatterns = { "/ServletDownload" })  
  19. public class ServletDownload extends HttpServlet {  
  20.     private static final long serialVersionUID = 1L;  
  21.          
  22.     /** 
  23.      * @see HttpServlet#HttpServlet() 
  24.      */  
  25.     public ServletDownload() {  
  26.         super();  
  27.         // TODO Auto-generated constructor stub  
  28.     }  
  29.   
  30.     /** 
  31.      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
  32.      */  
  33.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  34.         // TODO Auto-generated method stub  
  35.           
  36.         //获得请求文件名  
  37.         String filename = request.getParameter("filename");  
  38.         System.out.println(filename);  
  39.           
  40.         //设置文件MIME类型  
  41.         response.setContentType(getServletContext().getMimeType(filename));  
  42.         //设置Content-Disposition  
  43.         response.setHeader("Content-Disposition""attachment;filename="+filename);  
  44.         //读取目标文件,通过response将目标文件写到客户端  
  45.         //获取目标文件的绝对路径  
  46.         String fullFileName = getServletContext().getRealPath("/download/" + filename);  
  47.         //System.out.println(fullFileName);  
  48.         //读取文件  
  49.         InputStream in = new FileInputStream(fullFileName);  
  50.         OutputStream out = response.getOutputStream();  
  51.           
  52.         //写文件  
  53.         int b;  
  54.         while((b=in.read())!= -1)  
  55.         {  
  56.             out.write(b);  
  57.         }  
  58.           
  59.         in.close();  
  60.         out.close();  
  61.     }  
  62.   
  63.     /** 
  64.      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
  65.      */  
  66.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  67.         // TODO Auto-generated method stub  
  68.     }  
  69.   
  70. }  

重启tomcat服务器,即可实现对压缩包和对图片的下载。




-------------------------------------------------------------------------以上内容转自http://blog.csdn.net/longshengguoji/article/details/39433307--------------------------------------------------------



此外,还有一种下载情况-------------下载其他服务器上的文件

此时,需要使用http将其他服务器文件保存至本地,然后如果有下载需求再另行下载操作。


如下代码实现从其他服务器保存代码至本地:


public class FileUtilz {

    public boolean saveUrlAs(String photoUrl, String fileName) {
        // 此方法只能用户HTTP协议
        System.out.println("photoUrl = " + photoUrl);
        System.out.println("fileName = " + fileName);

        try {
            URL url = new URL(photoUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            DataInputStream in = new DataInputStream(connection.getInputStream());
            DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName));
            byte[] buffer = new byte[4096];
            int count = 0;
            while ((count = in.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
            out.close();
            in.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public String getDocumentAt(String urlString) {
        // 此方法兼容HTTP和FTP协议
        StringBuffer document = new StringBuffer();
        try {
            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                document.append(line + "\n");
            }
            reader.close();
        } catch (MalformedURLException e) {
            System.out.println("Unable to connect to URL: " + urlString);
        } catch (IOException e) {
            System.out.println("IOException when connecting to URL: " + urlString);
        }
        return document.toString();
    }

    public static void main(String[] args) {

        FileUtilz t = new FileUtilz();
        String photoUrl = "http://61.178.11.86:9330/agengr/test.jpg";
        String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
        String filePath = "D:/aaaaa";
        boolean flag = t.saveUrlAs(photoUrl, filePath + fileName);
        System.out.print("下载状态:" + flag);

    }

}

如需下载,代码类似如下:

String downloadUrl=“http://61.178.11.86:9330/agengr/test.jpg”;

public String downloadInvoice(){
        OutputStream outp = null;
        FileInputStream in = null;
        
        try {
            Assert.notNull(downloadUrl);
            
            
            FileUtilz t = new FileUtilz();
            String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1, downloadUrl.length());
            String filePath = "D:/aaaaa/" + fileName;
            boolean flag = t.saveUrlAs(downloadUrl, filePath);
            
            if(flag){
                
                fileName = URLEncoder.encode(fileName, "UTF-8");
                getReponse().addHeader("Content-Disposition", "attachment;filename=" + fileName);
            
                outp = getReponse().getOutputStream();
                in = new FileInputStream(filePath);

                byte[] b = new byte[1024];
                int i = 0;

                while ((i = in.read(b)) > 0) {
                    outp.write(b, 0, i);
                }
                
                outp.flush();
                
            }else {
                logger.error("下载失败。。。");
            }
            
            
            
        } catch (Exception e) {
            logger.error("下载发票出错", e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                    in = null;
                }
            } catch (Exception e) {
                logger.error("下载发票,关闭输入输出流出错", e);
            }
        }
        
        return null;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值