jProgressBar
の間にその値を更新したいHTTP 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);
正しいですか?