【问题标题】:Get the upload progress获取上传进度
【发布时间】:2012-02-06 16:37:05
【问题描述】:

我的上传方法如下:

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(); 花费的时间最多。 但是如何获得它发送的进度呢? 或者如何修改我的“按部分”上传文件的方法?

【问题讨论】:

标签: java android


【解决方案1】:

你可以试试下面的代码,

在调用你的上传方法之前,首先显示一个进度对话框,

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

【讨论】:

  • 我的意思是我不知道如何获取已发送的字节。
  • 是的。但我不知道如何取得进展。
  • //你的上传代码在这里,你需要在run方法中写你的方法代码。
  • 不,不是那样,只需将整个方法的调用放在 run 方法中即可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-01
  • 2017-09-09
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
相关资源
最近更新 更多