2012-02-06 85 views
2

我上傳方法如下:獲取上傳進度

private void upload(String Server, String FilePath, String SavePath, String NewName) { 
String end = "\r\n"; 
String twoHyphens = "--"; 
String boundary = "*****"; 
try { 
URL url = new URL(ActionUrl); 
HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
con.setDoInput(true); 
con.setDoOutput(true); 
con.setUseCaches(false); 
con.setRequestMethod("POST"); 
con.setRequestProperty("Connection", "Keep-Alive"); 
con.setRequestProperty("Accept", "text/*"); 
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); 
ds = new DataOutputStream(con.getOutputStream()); 
ds.writeBytes(twoHyphens + boundary + end); 
ds.writeBytes("Content-Disposition: form-data;" + "name=\"folder\"" + end + end); 
ds.write(SavePath.getBytes("UTF-8")); 
ds.writeBytes(end); 
ds.writeBytes(twoHyphens + boundary + end); 
ds.writeBytes("Content-Disposition: form-data;" + "name=\"Filedata\"; filename=\""); 
ds.write(NewName.getBytes("UTF-8")); 
ds.writeBytes("\"" + end); 
ds.writeBytes(end); 

FileInputStream fStream = new FileInputStream(uploadFile); 
int bufferSize = 1024; 
byte[] buffer = new byte[bufferSize]; 
int length = -1; 
while((length = fStream.read(buffer)) != -1) { 
ds.write(buffer, 0, length); 
}  
ds.writeBytes(end); 
ds.writeBytes(twoHyphens + boundary + twoHyphens + end); 

fStream.close(); 
ds.flush(); 
InputStream is = con.getInputStream(); 
int ch; 
StringBuffer b = new StringBuffer(); 
while((ch = is.read()) != -1) { 
b.append((char)ch); 
} 
System.out.println("UPLOAD" + "SUCCESS"); 
ds.close(); 
} 
catch(Exception e) { 
e.printStackTrace(); 
} 
} 

我發現行InputStream is = con.getInputStream();花費大量的時間。 但是如何讓它的進度發送? 或如何修改我的方法上傳文件「按部分」?

+0

看看這可以幫助你...... http://stackoverflow.com/questions/3739626/upload-file-or-inputstream-to-s3-with-a-progress-callback – 2012-02-06 07:50:46

回答

4

你可以試試下面的代碼,

首先顯示進度對話框調用上傳方法之前,

progDailog = ProgressDialog.show(loginAct,"Process ", "please wait....",true,true); 

new Thread (new Runnable() 
{ 
    public void run() 
    { 
     // your uploading code goes here 
    } 
}).start(); 

Handler progressHandler = new Handler() 
{ 

    public void handleMessage(Message msg1) 
    { 

     progDailog.dismiss(); 
     } 
} 
+0

我的意思是我不知道如何獲取已發送的字節。 – brian 2012-02-06 08:02:20

+0

你的意思是從你的記憶中讀取文件? – Lucifer 2012-02-06 08:06:29

+0

從內存到服務器 – brian 2012-02-06 08:14:28