2

我希望我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);正确吗?

4

2 回答 2

6

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

于 2012-05-06T13:51:24.617 回答
3

我赞同@Marko Topolnic 关于使用SwingWorker的建议, 看看这些有用的链接,让您进一步了解Howto

  1. 如何使用进度条
  2. Swing 中的并发性
  3. 工作线程和 SwingWorker

和@trashgod 的一个例子

于 2012-05-06T14:11:34.057 回答