超大文件上传到服务器,实现流式传输,不再出现java.lang.OutOfMemoryError: Java heap space...

本文介绍如何使用 Java 的 HttpURLConnection 进行文件上传操作,包括设置请求方式、读取本地文件并将其发送到指定 URL 的过程。同时提供了一种更稳定的获取服务器返回值的方法。
 

特别注意: HttpURLConnection要使用sun.net.www.protocol.http.HttpURLConnection

 

参考地址:http://ferreousbox.javaeye.com/blog/157728 

 

 代码如下:

 

 1  FileInputStream fis  = new  FileInputStream( new  File( " 本地文件地址 " ));
 2          URL dataUrl  =   new  URL( " 上传url " );
 3          HttpURLConnection con  =  (HttpURLConnection) dataUrl.openConnection();
 4          con.setRequestMethod( " POST " );
 5          con.setRequestProperty( " Proxy-Connection " " Keep-Alive " );
 6          con.setDoOutput( true );
 7          con.setDoInput( true );
 8          con.setChunkedStreamingMode( 1024 );
 9          OutputStream os = con.getOutputStream();
10           int  rn2;  
11           byte [] buf2  =   new   byte [ 1024 ];  
12           while ((rn2 = fis.read(buf2,  0 1024 )) > 0 )  
13          {     
14              os.write(buf2, 0 ,rn2);    
15              System.out.println( " 上传了1024... " );
16          }  
17          os.flush();  
18          os.close();  
19          fis.close();  
20          
21          InputStream is = con.getInputStream();
22          DataInputStream dis = new  DataInputStream(is);
23           byte  d[] = new   byte [dis.available()];
24          dis.read(d);
25          String data = new  String(d);
26          con.disconnect();
27          System.out.println(data);

 

 

 取返回值用下在这种方法会更好一点,上面的发现常出现取不到返回值的情况

 

ExpandedBlockStart.gif 代码
 BufferedReader inss  =   new  BufferedReader( new  InputStreamReader(con.getInputStream()));  
        String line 
=   null ;  
        StringBuffer content
=   new  StringBuffer();  
       
while ((line  =  inss.readLine())  !=   null ){ // line为返回值,这就可以判断是否成功、  
           content.append(line);  
       }  
       inss.close() ;  
       inss
= null ;  
       dataUrl 
=   null ;
       String data 
= content.toString();

 

 

 

转载于:https://www.cnblogs.com/cerxp/archive/2010/04/27/1721973.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值