2016-11-09 68 views
0

我想上传文件到服务器。文件成功上传,但我的问题是进度对话框直接变为0到100%或(0-50%-100%)。它不显示根据文件上传。请告诉我应该在这个代码进行编辑...Android进度对话框直接进入100%,而上传文件

public class ShowStudent extends AppCompatActivity implements View.OnClickListener{ 

private TextView messageText; 
private Button uploadButton, btnselectfile; 
private int serverResponseCode = 0; 
private ProgressDialog dialog = null; 
private String upLoadServerUri = null; 
private String filePath=null; 
@Override 
public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_show_student); 

    uploadButton = (Button)findViewById(R.id.uploadButton); 
    messageText = (TextView)findViewById(R.id.messageText); 
    btnselectfile = (Button)findViewById(R.id.button_selectfile); 
    uploadButton.setOnClickListener(this); 
    upLoadServerUri = "http://onsitesupport.info/diary/uploadproject.php"; 
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ 
     if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ 
      requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100); 
      return; 
     } 
    } 
    enable_button(); 
} 
@Override 
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 
    if(requestCode == 100 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)){ 
     enable_button(); 
    }else { 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100); 
     } 
    } 
} 
@Override 
public void onClick(View arg0) { 
    if (arg0==uploadButton) { 
     dialog =new ProgressDialog(ShowStudent.this); 
     dialog.setIndeterminate(false); 
     dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     dialog.setCancelable(true); 
     dialog.setMax(100); 
     dialog.show(); 
     messageText.setText("uploading started....."); 
     new Thread(new Runnable() { 
      public void run() { 
       uploadFile(filePath); 
      } 
     }).start(); 
    } 
} 
public void enable_button(){ 
    btnselectfile.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      new MaterialFilePicker() 
        .withActivity(ShowStudent.this) 
        .withRequestCode(10) 
        .withFilterDirectories(true) 
        .start(); 
     } 
    }); 
} 
@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == 10 && resultCode == RESULT_OK) { 
     File f = new File(data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH)); 
     filePath = f.getAbsolutePath(); 
     // String mimeType= URLConnection.guessContentTypeFromName(f.getName()); 
     messageText.setText("Uploading file path:" +filePath); 
    } 
} 
public int uploadFile(String sourceFileUri) { 
    String fileName = sourceFileUri; 
    HttpURLConnection conn = null; 
    DataOutputStream dos = null; 
    String lineEnd = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary = "*****"; 
    int bytesRead, bytesAvailable, bufferSize; 
    byte[] buffer; 
    int maxBufferSize = 1 * 1024 * 1024; 
    File sourceFile = new File(sourceFileUri); 
    if (!sourceFile.isFile()) { 
     dialog.dismiss(); 
     Log.e("uploadFile", "Source File not exist :"+filePath); 
     runOnUiThread(new Runnable() { 
      public void run() { 
       messageText.setText("Source File not exist :"+filePath); 
      } 
     }); 
     return 0; 
    } 
    else 
    { 
     try { 
      // open a URL connection to the Servlet 
      FileInputStream fileInputStream = new FileInputStream(sourceFile); 
      URL url = new URL(upLoadServerUri); 
      // Open a HTTP connection to the URL 
      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("uploaded_file", fileName); 
      dos = new DataOutputStream(conn.getOutputStream()); 
      dos.writeBytes(twoHyphens + boundary + lineEnd); 
      dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" 
        + fileName + "\"" + lineEnd); 
      dos.writeBytes(lineEnd); 
      // create a buffer of maximum size 
      bytesAvailable = fileInputStream.available(); 
      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      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); 
       sentBytes += bufferSize; 
       dialog.setProgress((int)(sentBytes * 100/bytesAvailable)); 
       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); 
      // Responses from the server (code and message) 
      serverResponseCode = conn.getResponseCode(); 
      String serverResponseMessage = conn.getResponseMessage(); 
      Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); 
      if(serverResponseCode == 200){ 
       runOnUiThread(new Runnable() { 
        public void run() { 
         String msg = "File Upload Completed.\n\n See uploaded file here : \n\n" 
           +" F:/wamp/wamp/www/uploads"; 
         messageText.setText(msg); 
         Toast.makeText(getBaseContext(), "File Upload Complete.", Toast.LENGTH_SHORT).show(); 
        } 
       }); 
      } 
      //close the streams // 
      fileInputStream.close(); 
      dos.flush(); 
      dos.close(); 
     } catch (MalformedURLException ex) { 
      dialog.dismiss(); 
      ex.printStackTrace(); 
      runOnUiThread(new Runnable() { 
       public void run() { 
        messageText.setText("MalformedURLException Exception : check script url."); 
        Toast.makeText(getBaseContext(), "MalformedURLException", Toast.LENGTH_SHORT).show(); 
       } 
      }); 
      Log.e("Upload file to server", "error: " + ex.getMessage(), ex); 
     } catch (Exception e) { 
      dialog.dismiss(); 
      e.printStackTrace(); 
      runOnUiThread(new Runnable() { 
       public void run() { 
        messageText.setText("Got Exception : see logcat "); 
        Toast.makeText(getBaseContext(), "Got Exception : see logcat ", Toast.LENGTH_SHORT).show(); 
       } 
      }); 
      // Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); 
     } 
     dialog.dismiss(); 
     return serverResponseCode; 
    } // End else block 
} 

}

回答

0

也许这是因为conn.getOutputStream()返回的流在内部进行缓冲。因此,当您发送小文件时,对话框不会显示写入网络的进度,而是写入该内部缓冲区的进度。为确保您可以添加

dos.flush(); 

在循环中执行每个写操作之后。它应该阻塞,直到数据写入网络。当然,这种黑客会降低总体上传性能。至少有两个选择:

  • 找到另一种方式来获得确实被写入网络的字节数
  • 执行flush()不是经常,例如说你是从后台线程调用

    dialog.setProgress((int)(sentBytes * 100/bytesAvailable)); 
    

    数据的一些理智的金额(例如,几KB)

+0

没有工作的兄弟...请建议我该怎么办.. –

0

的写作之后。为了更新UI,你必须从UI线程中调用这个方法。

+0

不工作兄弟。尝试runOnUiThread ..仍然是同样的问题 –