我从android上传文件(视频和照片)到php服务器 我使用这段代码:
@SuppressWarnings("deprecation")
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
Utils.d(Config.REST_SERVER + url_connect);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.REST_SERVER+url_connect);
try {
@SuppressWarnings("deprecation")
MultipartEntity entity = new MultipartEntity();
entity.addPart("userId", new StringBody(this.userId));
entity.addPart("orderId", new StringBody(this.orderId));
Utils.d("size totale avant : "+this.files.size());
int i = 0;
for(File f:this.files){
entity.addPart("nameFile", new StringBody(f.getName()));
i++;
entity.addPart("files[]", (ContentBody) new FileBody(f));
}
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
Log.d("Create Response", json);
jObj = new JSONObject(json);
Log.d("Create Response", jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
我想制作与文件一样多的进度条,这些进度条将根据发送到服务器的字节百分比更改状态
有什么办法吗
提前谢谢你
最佳答案
像这样尝试。
供引用GitHub在上传 时显示Horizontal ProgressBar
的开源项目。它将在 ProgressBar
中显示 % of byte 上传。
public class MyMultipartEntity extends MultipartEntity{
private final ProgressListener listener;
public MyMultipartEntity(final ProgressListener listener)
{
super();
this.listener = listener;
}
public MyMultipartEntity(final HttpMultipartMode mode, final ProgressListener listener)
{
super(mode);
this.listener = listener;
}
public MyMultipartEntity(HttpMultipartMode mode, final String boundary, final Charset charset, final ProgressListener listener)
{
super(mode, boundary, charset);
this.listener = listener;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException
{
super.writeTo(new CountingOutputStream(outstream, this.listener));
}
public static interface ProgressListener
{
void transferred(long num);
}
public static class CountingOutputStream extends FilterOutputStream
{
private final ProgressListener listener;
private long transferred;
public CountingOutputStream(final OutputStream out, final ProgressListener listener)
{
super(out);
this.listener = listener;
this.transferred = 0;
}
public void write(byte[] b, int off, int len) throws IOException
{
out.write(b, off, len);
this.transferred += len;
this.listener.transferred(this.transferred);
}
public void write(int b) throws IOException
{
out.write(b);
this.transferred++;
this.listener.transferred(this.transferred);
}
}
}
如何在AsyncTask中使用它来展示ProgressBar
public class HttpUpload extends AsyncTask<Void, Integer, Void> {
private Context context;
private String imgPath;
private HttpClient client;
private ProgressDialog pd;
private long totalSize;
private static final String url = "YOUR_URL";
public HttpUpload(Context context, String imgPath) {
super();
this.context = context;
this.imgPath = imgPath;
}
@Override
protected void onPreExecute() {
//Set timeout parameters
int timeout = 10000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
HttpConnectionParams.setSoTimeout(httpParameters, timeout);
//We'll use the DefaultHttpClient
client = new DefaultHttpClient(httpParameters);
pd = new ProgressDialog(context);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("Uploading Picture/Video...");
pd.setCancelable(false);
pd.show();
}
@Override
protected Void doInBackground(Void... params) {
try {
File file = new File(imgPath);
//Create the POST object
HttpPost post = new HttpPost(url);
//Create the multipart entity object and add a progress listener
//this is a our extended class so we can know the bytes that have been transfered
MultipartEntity entity = new MyMultipartEntity(new ProgressListener()
{
@Override
public void transferred(long num)
{
//Call the onProgressUpdate method with the percent completed
publishProgress((int) ((num / (float) totalSize) * 100));
Log.d("DEBUG", num + " - " + totalSize);
}
});
//Add the file to the content's body
ContentBody cbFile = new FileBody( file, "image/jpeg" );
entity.addPart("source", cbFile);
//After adding everything we get the content's lenght
totalSize = entity.getContentLength();
//We add the entity to the post request
post.setEntity(entity);
//Execute post request
HttpResponse response = client.execute( post );
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == HttpStatus.SC_OK){
//If everything goes ok, we can get the response
String fullRes = EntityUtils.toString(response.getEntity());
Log.d("DEBUG", fullRes);
} else {
Log.d("DEBUG", "HTTP Fail, Response Code: " + statusCode);
}
} catch (ClientProtocolException e) {
// Any error related to the Http Protocol (e.g. malformed url)
e.printStackTrace();
} catch (IOException e) {
// Any IO error (e.g. File not found)
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
//Set the pertange done in the progress dialog
pd.setProgress((int) (progress[0]));
}
@Override
protected void onPostExecute(Void result) {
//Dismiss progress dialog
pd.dismiss();
}
}
希望对您有所帮助。
关于android - 将多个文件上传到android中的服务器时的进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19662846/