gpt4 book ai didi

带有 HTTP 上传的 Java ProgressBar 不更新

转载 作者:行者123 更新时间:2023-12-03 01:55:26 25 4
gpt4 key购买 nike

我希望我的 jProgressBarHTTP 文件上传 期间更新其值。我是 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 并将您的工作委托(delegate)给它。

关于带有 HTTP 上传的 Java ProgressBar 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10471001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com