3

ファイルのアップロード中に進行状況を表示することになっている非同期タスクがあります。ファイルのアップロードが非常に速く完了したように見えることを除いて、すべてが機能しています。その後、100%待機しているだけです。

私はこれをたどりました

URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();

// 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;boundary=" + boundary);

outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"Filedata\";filename=\"" + pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
long totalBytesWritten = 0;
while (bytesRead > 0) {
    outputStream.write(buffer, 0, bufferSize);
    outputStream.flush();
    if (mCancel) { throw new CancelException(); }

    totalBytesWritten += bufferSize;
    if (mProgressDialog != null) { 
            mProgressDialog.setProgress(Integer.valueOf((int) (totalBytesWritten / 1024L))); 
    }

    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();

私が気付いたのは、応答コードを取得する最後の行まで実際の遅延がないことです。何が起こっているのかというと、データがバッファリングされているため、アップロードされたように見えますが、実際にはバッファリングされていません。次に、getResponseCode()呼び出しに到達すると、アップロードを終了してアップロードステータスを取得する以外に選択肢はありません。途中で実際にアップロードして、合理的な進捗を得る方法はありますか?

4

5 に答える 5

2

これは、HTTP Post が機能するように設計されているため、進行状況の詳細を提供することを期待しないでください。

市場で入手可能ないくつかのファイル アップローダ コンポーネントのいずれかを使用できます。彼らは内部的にフラッシュ、シルバーライト、または iframe を使用して進行状況を表示します。

http://dhtmlx.com/docs/products/dhtmlxVault/index.shtml

http://www.element-it.com/multiple-file-upload/flash-uploader.aspx

少しグーグルで検索すると、他にもそのようなものがたくさん見つかります。

複数のファイルと進行状況の通知を処理するために、http ポストの代わりに raw IO を内部的に使用します。Yahoo と Google も、メールに添付ファイルを作成するためにこのような手法を使用しています。

本当に冒険したい場合は、ホイールを再作成できます。つまり、独自のコンポーネントを作成します。

編集:

これを Windows デスクトップ アプリケーションまたは Web アプリケーションのどちらで実行するかを指定してください。

于 2012-09-10T06:10:19.263 に答える
0

AsyncTask を使用して試すことができます...

onPreExecute メソッドで進行状況ダイアログを作成し、onPostExecute メソッドでダイアログを閉じます。

アップロード メソッドを doInBackground() に保持する

例 :

public class ProgressTask extends AsyncTask<String, Void, Boolean> {

    public ProgressTask(ListActivity activity) {
        this.activity = activity;
        dialog = new ProgressDialog(context);
    }

    /** progress dialog to show user that the backup is processing. */
    private ProgressDialog dialog;

    protected void onPreExecute() {
        this.dialog.setMessage("Progress start");
        this.dialog.show();
    }

        @Override
    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }           
    }

    protected Boolean doInBackground(final String... args) {

// アップロード コード

          return true;
       }
    }
}
于 2012-09-10T06:28:37.380 に答える
0

Progress Dialog クラスは次のように使用できます。

ProgressDialog progDailog = ProgressDialog.show(this,"Uploading", "Uploading File....",true,true);

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

Handler progressHandler = new Handler() 
{
     public void handleMessage(Message msg1) 
     {
         progDailog.dismiss();
     }
}
于 2012-09-10T06:06:41.427 に答える
0

あなたは次のようにすることができます:

try { // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(
                    sourceFile);
            URL url = new URL("http://10.0.2.2:9090/plugins/myplugin/upload");
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploadedfile", filename);
            // conn.setFixedLengthStreamingMode(1024);
            // conn.setChunkedStreamingMode(1);
            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + filename + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            bytesAvailable = fileInputStream.available();
            bufferSize = (int) sourceFile.length()/200;//suppose you want to write file in 200 chunks
            buffer = new byte[bufferSize];
            int sentBytes=0;
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                // Update progress dialog
                sentBytes += bufferSize;
                publishProgress((int)(sentBytes * 100 / bytesAvailable));
                bytesAvailable = fileInputStream.available();
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();
            // close streams
            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
于 2013-09-16T05:46:49.600 に答える