带有HTTP上载的Java ProgressBar不会更新

时间:2012-05-06 13:47:00

标签: java swing file-upload java-io jprogressbar

我希望我的jProgressBarHTTP File Upload期间更新其值。 我是Java的新手,我不确定我做的是正确的事情,这是我的代码:

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);是否正确?

2 个答案:

答案 0 :(得分:6)

此处标记为java的每30个问题中就有一个与您的解决方案相同。您正在事件处理程序中完成所有工作,这意味着它发生在事件调度线程上 - 并阻止所有进一步的GUI更新,直到它结束。您必须使用SwingWorker并将您的工作委托给它。

答案 1 :(得分:3)

我的第二个@Marko Topolnic建议使用SwingWorker,看一下这些有用的链接,以便进一步了解 Howto

  1. How to Use Progress Bars
  2. Concurrency in Swing
  3. Worker Threads and SwingWorker
  4. example @trashgod。