2012-05-06 35 views
2

我希望我的jProgressBarHTTP File Upload期間更新其值。 我是新來的Java,我不知道我在做正確的事情,這是我的代碼:帶HTTP上傳的Java ProgressBar不更新

private static final String Boundary = "--7d021a37605f0"; 

public void upload(URL url, File f) throws Exception 
{ 
    HttpURLConnection theUrlConnection = (HttpURLConnection) url.openConnection(); 
    theUrlConnection.setDoOutput(true); 
    theUrlConnection.setDoInput(true); 
    theUrlConnection.setUseCaches(false); 
    theUrlConnection.setChunkedStreamingMode(1024); 

    theUrlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" 
      + Boundary); 

    DataOutputStream httpOut = new DataOutputStream(theUrlConnection.getOutputStream()); 


     String str = "--" + Boundary + "\r\n" 
        + "Content-Disposition: form-data;name=\"file1\"; filename=\"" + f.getName() + "\"\r\n" 
        + "Content-Type: image/png\r\n" 
        + "\r\n"; 

     httpOut.write(str.getBytes()); 

     FileInputStream uploadFileReader = new FileInputStream(f); 
     int numBytesToRead = 1024; 
     int availableBytesToRead; 
     jProgressBar1.setMaximum(uploadFileReader.available()); 
     while ((availableBytesToRead = uploadFileReader.available()) > 0) 
     { 
      jProgressBar1.setValue(jProgressBar1.getMaximum() - availableBytesToRead); 
      byte[] bufferBytesRead; 
      bufferBytesRead = availableBytesToRead >= numBytesToRead ? new byte[numBytesToRead] 
        : new byte[availableBytesToRead]; 
      uploadFileReader.read(bufferBytesRead); 
      httpOut.write(bufferBytesRead); 
      httpOut.flush(); 
     } 
     httpOut.write(("--" + Boundary + "--\r\n").getBytes()); 

    httpOut.flush(); 
    httpOut.close(); 

    // read & parse the response 
    InputStream is = theUrlConnection.getInputStream(); 
    StringBuilder response = new StringBuilder(); 
    byte[] respBuffer = new byte[4096]; 
    while (is.read(respBuffer) >= 0) 
    { 
     response.append(new String(respBuffer).trim()); 
    } 
    is.close(); 
    System.out.println(response.toString()); 
} 

這是行jProgressBar1.setValue(jProgressBar1.getMaximum() - availableBytesToRead);正確嗎?

回答

6

像標籤爲java的每30個問題中的一個就像您的解決方案一樣。您正在事件處理程序中完成所有工作,這意味着它發生在事件派發線程上 - 並阻止所有進一步的GUI更新,直到它結束。您必須使用SwingWorker並將您的工作委託給它。

+0

好的,感謝您的回答,但是我怎樣才能從工作人員處獲取上傳進度? – user1376701

+0

你有什麼試過的?你有沒有編譯失敗的代碼,或者在運行時,你有沒有將引用'jProgressBar1'分享給其他線程的問題......? –