我已经编写了以下代码来通过服务器上传 wav 文件,我面临的问题是进度条移动得太快,直到 99% 并且一旦服务器返回 200 OK 响应就完成。
但我在 Dropbox 中看到,当我上传文件时,我可以看到进度条正在逐渐移动,看起来很有说服力。
任何人都知道我如何显示无缝进度条。
@Override
protected String doInBackground(Void...args) {
// TODO Auto-generated method stub
System.out.println(uploadLink);
FileInputStream sourceFile = null;
try {
sourceFile = new FileInputStream(to);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
URL url;
try {
byte[] bytes = new byte[(int) to.length()];
sourceFile.read(bytes);
url = new URL(uploadLink);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
out = new DataOutputStream( connection.getOutputStream() );
out.writeBytes(twoHyphens + boundary + lineEnd);
out.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + templateID + ".wav" + "\"" + lineEnd);
out.writeBytes(lineEnd);
bytesAvailable = sourceFile.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
Log.d("BYTES" , bytesAvailable + " "+bufferSize +" "+ bytes.length);
int bufferLength = 1024;
for (int i = 0; i < bytes.length; i += bufferLength) {
int progress = (int)((i / (float) bytes.length) * 100);
publishProgress(progress);
if (bytes.length - i >= bufferLength) {
out.write(bytes, i, bufferLength);
} else {
out.write(bytes, i, bytes.length - i);
}
}
out.writeBytes(lineEnd);
out.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
sourceFile.close();
out.flush();
out.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
try {
in = new DataInputStream ( connection.getInputStream() );
String str;
Log.d("STATUS",connection.getResponseCode()+ " ");
if(connection.getResponseCode() == 200)
{
while (( str = in.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
publishProgress(100);
}
}
in.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
// Get the source File
return "success";
}