8

私はしばらくこれにこだわっています。画像を Web サーバーにアップロードする非同期タスクがあります。正常に動作します。

このためにプログレスバーダイアログを設定しています。私の問題は、進行状況バーを正確に更新する方法です。私が試したすべての結果は、0 から 100 まで 1 ステップで進みます。5秒でも2分でも構いません。アップロードが完了すると、バーが 0 に止まり、100 に達します。

これが私の doInBackground コードです。どんな助けでも大歓迎です。

編集: 以下のコードを更新して、AsynchTask 全体を含めました。

private class UploadImageTask extends AsyncTask<String,Integer,String> {

        private Context context;   
        private String msg = "";
        private boolean running = true;

        public UploadImageTask(Activity activity) {
            this.context = activity;
            dialog = new ProgressDialog(context);
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setMessage("Uploading photo, please wait.");
            dialog.setMax(100);
            dialog.setCancelable(true);
        }


    @Override
    protected void onPreExecute() {
            dialog.show();
            dialog.setOnDismissListener(mOnDismissListener);
    }



    @Override
    protected void onPostExecute(String msg){

         try {
        // prevents crash in rare case where activity finishes before dialog
        if (dialog.isShowing()) {
                dialog.dismiss();
        }
              } catch (Exception e) {
              } 
     }


     @Override
     protected void onProgressUpdate(Integer... progress) {        
      dialog.setProgress(progress[0]);
     }








    @Override
    protected String doInBackground(String... urls) {

                if(running) {

                    // new file upload
                    HttpURLConnection conn = null;
                    DataOutputStream dos = null;
                    DataInputStream inStream = null;

                    String exsistingFileName = savedImagePath;
                    String lineEnd = "\r\n";
                    String twoHyphens = "--";
                    String boundary = "*****";

                    int bytesRead, bytesAvailable, bufferSize;
                    byte[] buffer;
                    int maxBufferSize = 1024 * 1024;

                    String urlString = "https://mysite.com/upload.php";
                    float currentRating = ratingbar.getRating();

                    File file = new File(savedImagePath);
                    int sentBytes = 0;
                    long fileSize = file.length();


                    try {
                        // ------------------ CLIENT REQUEST

                        // open a URL connection to the Servlet
                        URL url = new URL(urlString);
                        // Open a HTTP connection to the URL
                        conn = (HttpURLConnection) url.openConnection();
                        // Allow Inputs
                        conn.setDoInput(true);
                        // Allow Outputs
                        conn.setDoOutput(true);
                        // Don't use a cached copy.
                        conn.setUseCaches(false);
                        // Use a post method.
                        conn.setRequestMethod("POST");
                        conn.setRequestProperty("Connection", "Keep-Alive");
                        conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);


                        dos = new DataOutputStream(conn.getOutputStream());



                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                                        + exsistingFileName + "\"" + lineEnd);


                        dos.writeBytes(lineEnd);

                        FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName));
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        buffer = new byte[bufferSize];

                        // 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 / fileSize));

                            bytesAvailable = fileInputStream.available();
                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                        }

                        // send multipart form data necesssary after file data...
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                        dos.flush();
                        dos.close();
                        fileInputStream.close();
                    }catch (MalformedURLException e) {

                    }catch (IOException e) {

                    }


                    // ------------------ read the SERVER RESPONSE
                    try {
                        inStream = new DataInputStream(conn.getInputStream());

                        // try to read input stream
                        // InputStream content = inStream.getContent();
                        BufferedInputStream bis = new BufferedInputStream(inStream);
                        ByteArrayBuffer baf = new ByteArrayBuffer(20);

                        long total  = 0;
                        int current = 0;
                        while ((current = bis.read()) != -1) {
                        baf.append((byte) current);



                        /* Convert the Bytes read to a String. */
                        String mytext = new String(baf.toByteArray());
                        final String newtext = mytext.trim();

                        inStream.close();



                    } catch (Exception e) {

                    }
                }
                return msg;
        }



}
4

5 に答える 5

2

float 値で除算を行い、結果を int に戻す必要があります。

float progress = ((float)sentBytes/(float)fileSize)*100.0f;
publishProgress((int)progress);
于 2013-06-24T06:06:03.723 に答える
2

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

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:44:48.607 に答える
0

この例で 2 日間を費やします。

そして、すべてこの文字列にあります。

conn.setRequestProperty("ENCTYPE", "multipart/form-data");

それだけで助かります。

于 2015-07-22T16:07:50.333 に答える