[英]Java ProgressBar with HTTP Upload don't update
I want my jProgressBar
to update its value during HTTP File Upload
. 我希望我的jProgressBar
在HTTP File Upload
期间更新其值。 I'm new to Java and I'm not sure I'm doing the right things, here's my code: 我是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());
}
Is this line jProgressBar1.setValue(jProgressBar1.getMaximum() - availableBytesToRead);
这行是jProgressBar1.setValue(jProgressBar1.getMaximum() - availableBytesToRead);
correct ? 对吗?
Something like one in every 30 questions tagged java
here has the same solution as yours. 像这里标记为java
每30个问题中就有一个类似于你的解决方案。 You are doing all your work inside an event handler, which means that it's happening on the Event Dispatch Thread -- and blocks all further GUI updates until it's over. 您正在事件处理程序中完成所有工作,这意味着它发生在事件调度线程上 - 并阻止所有进一步的GUI更新,直到它结束。 You must use a SwingWorker
and delegate your work to it. 您必须使用SwingWorker
并将您的工作委托给它。
I second @Marko Topolnic's suggestion of using a SwingWorker , Have a look at these useful links to get you further on Howto , 我的第二个@Marko Topolnic建议使用SwingWorker ,看看这些有用的链接,让你进一步了解Howto ,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.