`
ootabc
  • 浏览: 110635 次
  • 性别: Icon_minigender_1
  • 来自: 湖南
社区版块
存档分类
最新评论

file down load

    博客分类:
  • java
阅读更多
转载:  http://blog.csdn.net/seng3018/archive/2010/02/22/5316178.aspx

     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;
    }

     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();
        }
    }

     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();
            FileOutputStream fs  =   new  FileOutputStream( " c:/abc.gif " );

             byte [] buffer  =   new   byte [ 1204 ];
             int  length;
             while  ((byteread  =  inStream.read(buffer))  !=   - 1 ) {
                bytesum  +=  byteread;
                System.out.println(bytesum);
                fs.write(buffer,  0 , byteread);
            }
        }  catch  (FileNotFoundException e) {
            e.printStackTrace();
        }  catch  (IOException e) {
            e.printStackTrace();
        }
    }
//支持在线打开文件的一种方式
     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();
    }

分享到:
评论

相关推荐

    wget - down load file from Dos prompt

    wget is a command line program. You start it from the command prompt in Windows. The command prompt can be found in the Start Menu (Accessories).

    react-native-up-down-load:用于查看,上传和下载任何类型文件的React-native组件。 最初支持android操作系统

    React Native Up Down Load 是一个专为React Native框架设计的组件,它允许开发者在Android平台上查看、上传和下载各种类型的文件。这个组件最初是为Android系统开发的,但随着React Native的发展,它可能也逐渐支持...

    即时通讯.7z

    即时通讯技术是现代互联网应用中的重要组成部分,尤其在社交、娱乐和商业领域有着广泛的应用。"即时通讯.7z"这个压缩包文件可能包含了实现一个即时通讯系统的必要组件,其中包括数据库文件和用户交互界面。...

    a-file-icon-3.2.1.zip_back

    The value of NumConnectedPixels needs to be passed back as a pointer, so the subroutine call for... Down load the image img22gd2.tif. Apply the subroutine ConnectedPixels to extract the connected set ...

    Android代码-CoolImageView

    Dynamic effect preview (Because the gif resources are large, please wait for the resources to complete the load) this is background picture left and right movement this is background picture move ...

    django的上传下载

    xxx.xxx.xxx.xxx:xxx/down/<str:file_name> 文件内容包括: load.html #上传 down.html #下载 views.py #服务器设置 -def load(request) -def down(request) -def down_str(request,file_name)

    Oray.rar 向日葵远程客户端

    向日葵远程客户端是一款强大的远程控制软件,专为个人用户和企业用户提供便捷、安全的远程访问解决方案。在本文中,我们将深入探讨向日葵远程客户端的功能、应用、优点以及如何使用它来实现远程操作。...

    【MATLAB源码】图片数据点提取.zip

    Load the image file. % 2. Calibrate axes dimensions. You will be prompted to select 4 points % on the image. Zoom and pan enabled. % 3. Grab points by clicking on points. Right-click to delete a ...

    BURNINTEST--硬件检测工具

    - When BurnInTest crashes, it will not generate a "minidump" file. Minidumps will need to be sent to Microsoft as per the normal process. However, a log entry will be added to the normal BurnIn...

    DB2pureScale_Practical_Design_Guide_2016-Feb-5.pptx

    3-7 Large buffer pool may slow down LOAD and REORG 3-8 Consider multiple table space containers 4. Tables and Index Design 4-1 Considerations for SEQUENCE and IDENTITY columns 4-2 First column ...

    王小平版遗传算法的光盘源代码

    is compiled into an object library file, which is then linked with the problem specific objects. Read the notes in the Makefiles in all the sub-directories, make any necessary changes to fit your ...

    java语言关于文件上传下载功能实例

    File fileToDownload = new File("uploads/somefile.txt"); FileInputStream fis = new FileInputStream(fileToDownload); response.setHeader("Content-Disposition", "attachment; filename=\"" + ...

    flash as3 加载外部swf jpg gif png loader urlloader的通用代码

    loads swf_btn.addEventListener(MouseEvent.MOUSE_DOWN, loadobject("1.jpg")); loadjpg_btn.addEventListener(MouseEvent.MOUSE_DOWN, loadobject("6.jpg")); ``` 这里的 `loadobject` 函数负责实际的资源加载...

    金卡制作工具GoldCardTool

    GoldCard Tool v0.0.5 Requirements: Spare microSD card Windows PC (Tested on Windows7 x64...Click 'Load GoldCard.img' and open the .img file you got by email. Click 'Patch MMC' You now have a goldcard!

    xlistview代码

    * @description An ListView support (a) Pull down to refresh, (b) Pull up to load more. * Implement IXListViewListener, and see stopRefresh() / stopLoadMore(). */ package ...

    CCS快捷键操作(中文版).pdf

    - **Load Program**:Ctrl+L - **Reload Program**:Ctrl+Shift+L - **Restart**:Ctrl+Shift+F5 - **Run**:F5 - **Run to cursor**:Ctrl+F10 - **Toggle breakpoint**:F9 - **Move to the end of file**:Ctrl+...

    php注入案例

    - **方法**: 利用 `LOAD_FILE()` 函数读取服务器上的文件。 - **示例**: 构造SQL语句 `http://www.******.net/down/show.php?id=100and1=2unionselectLOAD_FILE('C:/windows/win.ini')` 来读取 `win.ini` 文件。 - *...

    OutlookAttachView v2.73

    enough disk space to store the saved file. The drawback of this mode: You cannot sort the attachments according to the column you choose with /sort command-line option. * Version 2.30 o Added '...

    Turbo C 2.00[DISK]

    is load the file WORDCNT.C into the editor. Once you have done that, the rest of the instructions are correct. 5. ADDITIONAL NOTES -------------------- 5.1 NOTES FOR VERSION 1.0 & 1.5 USERS ---...

    RegClearner411.exe

    These will significantly increase the registry size and thus will slowdown your computer, because Windows will need more time to load, search, and read data from registry. To keep your computer in ...

Global site tag (gtag.js) - Google Analytics