【问题标题】:progress bar with uploading a file to an asp.net server将文件上传到 asp.net 服务器的进度条
【发布时间】:2012-07-03 14:04:17
【问题描述】:

我制作了一个将视频上传到 asp.net 服务器的程序。然后我想通过添加进度条来开发我的应用程序。但是,添加进度条后,我无法将文件上传到服务器。(这是我调试后得到的结果!!!)你能帮我看看我的代码有什么问题吗?

package com.isoft.uploader2;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class Proje2Activity extends Activity
{
 @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button =(Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                openGaleryVideo();
            }
        });

    }
/** Called when the activity is first created. */
public static final int SELECT_VIDEO=1;
public static final String TAG="UploadActivity";
String path="";

//Gallery'i aç
public void openGaleryVideo()
{
    Intent intent=new Intent();
    intent.setType("video/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Video"),SELECT_VIDEO);
}

//Dosyayı seç ve yükle
public void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK)
    {
        if (requestCode == SELECT_VIDEO) 
        {
            Uri videoUri = data.getData();
            path= getPath(videoUri);
            upload a = new upload();
            a.onPreExecute();
            a.doInBackground();
            a.onProgressUpdate();


        }
    }
}

//SD carddan yerini al
public String getPath(Uri uri)
{   
    String[] projection = { MediaStore.Video.Media.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
public class upload extends AsyncTask<Object, Integer, Void> 
{
     public ProgressDialog dialog;
     File file=new File(path);  
     String urlServer = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
     String filename=file.getName();
     int bytesRead, bytesAvailable, bufferSize;
     byte[] buffer;
     int maxBufferSize = 20*1024*1024;
    @Override
    public void onPreExecute() 
    {
         dialog = new ProgressDialog(Proje2Activity.this);
         dialog.setMessage("Uploading...");
         dialog.setIndeterminate(false);
         dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
         dialog.setProgress(0);
         dialog.show();
            //Burada işlemi yapmadan önce ilk olarak ne yaptırmak istiyorsak burada yaparız.
            //Örneğin burada dialog gösterip "onPostExecute()" metodunda dismiss edebiliriz.
    }

    @Override
    public Void doInBackground(Object... arg0) 
    {
        // TODO Auto-generated method stub
        try
        {
        FileInputStream fileInputStream = new FileInputStream(file);

        URL url = new URL(urlServer);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setFixedLengthStreamingMode((int) file.length());

        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // Enable POST method
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type",  "multipart/form-data");
        connection.setRequestProperty("SD-FileName", filename);//This will be the file name
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // Read file
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0)
        {   
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            publishProgress();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }//end of while statement
        fileInputStream.close();
        publishProgress(100); 
        outputStream.flush();
        outputStream.close();
        }//end of try body
        catch (Exception ex)
        {
            //ex.printStackTrace();
            Log.e("Error: ", ex.getMessage());
        }
        return null;
     }//end of doInBackground method
     @Override
     public void onProgressUpdate(Integer... values) 
     {
       // TODO Auto-generated method stub
       dialog.setProgress((int) ((file.length()-bytesRead)/100));
     }//end of onProgressUpdate method
}// end of asyncTask class 
}//end of main

【问题讨论】:

  • 在 VB.NET 中,URL 必须是这样的:'ftp.something.co.uk/htdocs' 但在 Android 中并不知道。也许检查 URL 是否正确?
  • URL 是正确的,因为我将文件上传到相同的 URL。
  • 上传一个 = new Upload(); a.execute();

标签: android file-upload android-asynctask progress-bar


【解决方案1】:

你必须调用上传任务像

new Upload().execute();

而你没有像以前那样调用 asynTask 来做正确的事情

所以你的代码如下所示

Upload a = new Upload();
a.execute 

代替

upload a = new upload();
            a.onPreExecute();
            a.doInBackground();
            a.onProgressUpdate();

如果您上传文件的代码是正确的,这将起作用

如果你想更新进度条使用 Handler 类

Handler handler = new Handler(){
    @Override 
    public void handleMessage(int what){
        mProgress.setProgress(mProgressStatus);
     }

ProgressBar widget中所述

并且在 doInBackground() 方法中调用方法 publishProgress() ,如此处所述AsyncTask Docs

【讨论】:

  • 那你有什么建议?如何将文件从 SD 卡上传到带有进度条的 asp.net 服务器?
  • 把上传n doInBackground()的代码,你做对了,只需使用execute方法调用Upload类
  • 我在我的应用程序中使用的是进度对话框而不是进度条。还适合用handler吗?
  • 是的,你可以使用你想要的任何东西,总是使用处理程序来更新进度对话框或栏
  • 感谢您的帮助,最后代码中的“什么”是什么?我不明白。是“进步”吗?
【解决方案2】:

正如 Muhannad 所说,您的 onActivityResult 方法应如下所示:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
    if (requestCode == SELECT_VIDEO) 
    {
        Uri videoUri = data.getData();
        path= getPath(videoUri);
        upload a = new upload();
        a.execute();


    }
}

}

编辑: 正如我的评论中所解释的。粗体更改:

public class upload extends AsyncTask<Object, Integer, Void> {
 public ProgressDialog dialog;
 File file=new File(path);  
 String urlServer = "http://192.168.10.177/androidweb/default.aspx";
 String filename=file.getName();
 int bytesRead, bytesAvailable, bufferSize, **progress**;
 byte[] buffer;
 int maxBufferSize = 20*1024*1024;
@Override
public void onPreExecute() 
{
     dialog = new ProgressDialog(Proje2Activity.this);
     dialog.setMessage("Uploading...");
     dialog.setIndeterminate(false);
     dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
     dialog.setProgress(0);
     dialog.show();
        //Burada işlemi yapmadan önce ilk olarak ne yaptırmak istiyorsak burada yaparız.
        //Örneğin burada dialog gösterip "onPostExecute()" metodunda dismiss edebiliriz.
}

@Override
public Void doInBackground(Object... arg0) 
{
    // TODO Auto-generated method stub
    try
    {
    FileInputStream fileInputStream = new FileInputStream(file);

    URL url = new URL(urlServer);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setFixedLengthStreamingMode((int) file.length());

    // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type",  "multipart/form-data");
    connection.setRequestProperty("SD-FileName", filename);//This will be the file name
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // Read file
    **progress = 0;**
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    **progress += bytesRead;**
    while (bytesRead > 0)
    {   
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        publishProgress();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        **progress += bytesRead;**
    }//end of while statement
    fileInputStream.close();
    publishProgress(100); 
    outputStream.flush();
    outputStream.close();
    }//end of try body
    catch (Exception ex)
    {
        //ex.printStackTrace();
        Log.e("Error: ", ex.getMessage());
    }
    return null;
 }//end of doInBackground method
 @Override
 public void onProgressUpdate(Integer... values) 
 {
   // TODO Auto-generated method stub
   dialog.setProgress((int) ((file.length()-**progress**)/100));
 }//end of onProgressUpdate method
 }// end of asyncTask class 
 }//end of main

【讨论】:

  • 谢谢,但是进度条仍然没有任何动作。我该如何解决这个问题?(关于更新栏)
  • 问题是bytesRead是这个周期的读取字节数,而不是总读取字节数。因此,为了获得总读取字节数,您必须将其累积在另一个变量中(例如 int progress += bytesRead;),并在 onProgressUpdate() 中取这个变量而不是 bytesRead 变量。我更新了代码
猜你喜欢
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 2012-04-11
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 2016-06-06
  • 2011-12-09
相关资源
最近更新 更多