Java ProgressBar,带HTTP上传don';t更新

Java ProgressBar,带HTTP上传don';t更新,java,swing,file-upload,java-io,jprogressbar,Java,Swing,File Upload,Java Io,Jprogressbar,我希望我的jProgressBar在HTTP文件上载期间更新其值。 我是Java新手,不确定自己做的事情是否正确,以下是我的代码: private static final String Boundary = "--7d021a37605f0"; public void upload(URL url, File f) throws Exception { HttpURLConnection theUrlConnection = (HttpURLConnection) url.openC

我希望我的
jProgressBar
HTTP文件上载期间更新其值。
我是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)正确吗?

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

我支持@Marko Topolnic关于使用的建议,请查看这些有用的链接,以进一步了解如何


  • 还有@trashgood的一封邮件。

    好的,谢谢你的回答,但是我怎样才能从工作人员那里获取上传进度呢?你尝试了什么?您是否有无法编译的代码,或者在运行时,您是否在将对
    jProgressBar1
    的引用共享到另一个线程时遇到问题…?非常感谢您和@Marko Topolnic!你的例子非常有用,我把我的函数放在一个独立的worker中,这很有效!