问题描述
我已经奔停留在这一段时间。我有一个异步任务上传图像到Web服务器。正常工作。
我有一个进度条对话框中设置了这一点。我的问题是如何准确地更新进度条。一切我尝试的结果是从0-100一步到位去。如果需要5秒或2分钟不要紧。酒吧挂到0,则达到100上传完成后。
下面是我的doInBackground code。任何帮助是AP preciated。
编辑:我更新下面的code到包括整个AsynchTask
私有类UploadImageTask扩展的AsyncTask<字符串,整数,字符串> {
私人上下文的背景下;
私人弦乐味精=;
私人布尔运行=真;
公共UploadImageTask(活动活动){
this.context =活动;
对话框=新ProgressDialog(上下文);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage(上传照片,请稍等。);
dialog.setMax(100);
dialog.setCancelable(真正的);
}
@覆盖
在preExecute保护无效(){
dialog.show();
dialog.setOnDismissListener(mOnDismissListener);
}
@覆盖
保护无效onPostExecute(弦乐味精){
尝试 {
// prevents在极少数情况下崩溃,其中的活性对话前完成
如果(dialog.isShowing()){
dialog.dismiss();
}
}赶上(例外五){
}
}
@覆盖
保护无效onProgressUpdate(整数...进度){
dialog.setProgress(进展[0]);
}
@覆盖
保护字符串doInBackground(字符串...网址){
如果(运行){
//新的文件上传
HttpURLConnection的康恩= NULL;
DataOutputStream类DOS = NULL;
inStream中的DataInputStream = NULL;
字符串exsistingFileName = savedImagePath;
字符串lineEnd =\ r \ N的;
串twoHyphens = - ;
字符串边界=*****;
INT读取动作,方bytesAvailable,缓冲区大小;
byte []的缓冲区;
INT maxBufferSize = 1024 * 1024;
字符串urlString =https://mysite.com/upload.php;
浮currentRating = ratingbar.getRating();
档案文件=新的文件(savedImagePath);
INT sentBytes = 0;
长文件大小= file.length();
尝试 {
// ------------------客户端请求
//打开一个URL连接到这个Servlet
网址URL =新的URL(urlString);
//打开一个HTTP连接网址
康恩=(HttpURLConnection类)url.openConnection();
//允许输入
conn.setDoInput(真正的);
//允许输出
conn.setDoOutput(真正的);
//不要使用缓存副本。
conn.setUseCaches(假);
//使用POST方法。
conn.setRequestMethod(POST);
conn.setRequestProperty(连接,保持活动);
conn.setRequestProperty(内容类型,多部分/格式数据;边界=+界);
DOS =新DataOutputStream类(conn.getOutputStream());
dos.writeBytes(twoHyphens +边界+ lineEnd);
dos.writeBytes(内容处置:表格数据;名称= \UploadedFile的\;文件名= \
+ exsistingFileName +\+ lineEnd);
dos.writeBytes(lineEnd);
的FileInputStream的FileInputStream =新的FileInputStream(新文件(exsistingFileName));
方bytesAvailable = fileInputStream.available();
BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
缓冲区=新的字节[BUFFERSIZE]
//读取文件,并将其写入形式...
读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);
而(读取动作大于0){
dos.write(缓冲液,0,BUFFERSIZE);
//更新进度对话框
sentBytes + = BUFFERSIZE;
publishProgress((INT)(sentBytes * 100 /文件大小));
方bytesAvailable = fileInputStream.available();
BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);
}
//发送多部分表格数据文件数据后necesssary ...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);
dos.flush();
dos.close();
fileInputStream.close();
}赶上(MalformedURLException异常E){
}赶上(IOException异常E){
}
// ------------------读取服务器响应
尝试 {
inStream中=新的DataInputStream(conn.getInputStream());
//尝试读取输入流
// InputStream的内容= inStream.getContent();
的BufferedInputStream双=新的BufferedInputStream(inStream中);
ByteArrayBuffer BAF =新ByteArrayBuffer(20);
总长= 0;
INT电流= 0;
而((电流= bis.read())!= - 1){
baf.append((字节)电流);
/ *读取转换为字符串的字节数。 * /
字符串MYTEXT =新的String(baf.toByteArray());
最后弦乐newtext = mytext.trim();
inStream.close();
}赶上(例外五){
}
}
返回味精;
}
}
这应该工作!
连接=(HttpURLConnection类)url_stripped.openConnection();
connection.setRequestMethod(PUT);
字符串边界=---------------------------边界;
字符串尾=\ r \ N--+边界+ - \ r \ N的;
connection.addRequestProperty(内容类型,图像/ JPEG);
connection.setRequestProperty(连接,保持活动);
connection.setRequestProperty(内容长度,
+ file.length());
connection.setDoOutput(真正的);
串metadataPart = -
+边界
+\ r \ N
+内容处置:表格数据;名称= \元数据\\ r \ñ\ r \ N
++\ r \ N的;
串fileHeader1 = -
+边界
+\ r \ N
+内容处置:表格数据;名称= \一个UploadFile \;文件名= \
+文件名+\\ r \ N
+内容类型:应用程序/八位字节流\ r \ N
+内容传输编码:二进制\ r \ N的;
长文件长度= file.length()+ tail.length();
字符串fileHeader2 =内容长度:+文件长度+\ r \ N的;
字符串FileHeader里= fileHeader1 + fileHeader2 +\ r \ N的;
字符串StringData是= metadataPart + FileHeader里;
长requestLength = stringData.length()+文件长度;
connection.setRequestProperty(内容长度,
+ requestLength);
connection.setFixedLengthStreamingMode((INT)requestLength);
connection.connect();
DataOutputStream类OUT =新DataOutputStream类(
connection.getOutputStream());
out.writeBytes(StringData是);
了out.flush();
INT进度= 0;
INT读取动作= 0;
中byte buf [] =新的字节[1024];
的BufferedInputStream bufInput =新的BufferedInputStream(
新的FileInputStream(文件));
而((读取动作= bufInput.read(BUF))!= -1){
//写输出
out.write(BUF,0,读取动作);
了out.flush();
进度+ =读取动作;
//更新进度条
publishProgress(进度);
}
//将关闭边界,靠近流
out.writeBytes(尾);
了out.flush();
out.close();
//获取服务器响应
的BufferedReader读卡器=新的BufferedReader(
新的InputStreamReader(connection.getInputStream()));
串线=;
StringBuilder的建设者=新的StringBuilder();
而((行= reader.readLine())!= NULL){
builder.append(线);
}
参考: http://delimitry.blogspot.in/2011/ 08 / Android的上载progress.html
I've ben stuck on this for a while. I have an asynch task that uploads an image to a web server. Works fine.
I'm have a progress bar dialog set up for this. My problem is how to accurately update the progress bar. Everything I try results in it going from 0-100 in one step. It doesn't matter if it takes 5 seconds or 2 minutes. The bar hangs onto 0 then hits 100 after the upload is done.
Here's my doInBackground code. Any help is appreciated.
EDIT: I updated the code below to include the entire AsynchTask
private class UploadImageTask extends AsyncTask<String,Integer,String> {
private Context context;
private String msg = "";
private boolean running = true;
public UploadImageTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage("Uploading photo, please wait.");
dialog.setMax(100);
dialog.setCancelable(true);
}
@Override
protected void onPreExecute() {
dialog.show();
dialog.setOnDismissListener(mOnDismissListener);
}
@Override
protected void onPostExecute(String msg){
try {
// prevents crash in rare case where activity finishes before dialog
if (dialog.isShowing()) {
dialog.dismiss();
}
} catch (Exception e) {
}
}
@Override
protected void onProgressUpdate(Integer... progress) {
dialog.setProgress(progress[0]);
}
@Override
protected String doInBackground(String... urls) {
if(running) {
// new file upload
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String exsistingFileName = savedImagePath;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
String urlString = "https://mysite.com/upload.php";
float currentRating = ratingbar.getRating();
File file = new File(savedImagePath);
int sentBytes = 0;
long fileSize = file.length();
try {
// ------------------ CLIENT REQUEST
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ exsistingFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName));
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
// Update progress dialog
sentBytes += bufferSize;
publishProgress((int)(sentBytes * 100 / fileSize));
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
fileInputStream.close();
}catch (MalformedURLException e) {
}catch (IOException e) {
}
// ------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
// try to read input stream
// InputStream content = inStream.getContent();
BufferedInputStream bis = new BufferedInputStream(inStream);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
long total = 0;
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
/* Convert the Bytes read to a String. */
String mytext = new String(baf.toByteArray());
final String newtext = mytext.trim();
inStream.close();
} catch (Exception e) {
}
}
return msg;
}
}
This should work !
connection = (HttpURLConnection) url_stripped.openConnection();
connection.setRequestMethod("PUT");
String boundary = "---------------------------boundary";
String tail = "\r\n--" + boundary + "--\r\n";
connection.addRequestProperty("Content-Type", "image/jpeg");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Length", ""
+ file.length());
connection.setDoOutput(true);
String metadataPart = "--"
+ boundary
+ "\r\n"
+ "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
+ "" + "\r\n";
String fileHeader1 = "--"
+ boundary
+ "\r\n"
+ "Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
+ fileName + "\"\r\n"
+ "Content-Type: application/octet-stream\r\n"
+ "Content-Transfer-Encoding: binary\r\n";
long fileLength = file.length() + tail.length();
String fileHeader2 = "Content-length: " + fileLength + "\r\n";
String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
String stringData = metadataPart + fileHeader;
long requestLength = stringData.length() + fileLength;
connection.setRequestProperty("Content-length", ""
+ requestLength);
connection.setFixedLengthStreamingMode((int) requestLength);
connection.connect();
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());
out.writeBytes(stringData);
out.flush();
int progress = 0;
int bytesRead = 0;
byte buf[] = new byte[1024];
BufferedInputStream bufInput = new BufferedInputStream(
new FileInputStream(file));
while ((bytesRead = bufInput.read(buf)) != -1) {
// write output
out.write(buf, 0, bytesRead);
out.flush();
progress += bytesRead;
// update progress bar
publishProgress(progress);
}
// Write closing boundary and close stream
out.writeBytes(tail);
out.flush();
out.close();
// Get server response
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Reference : http://delimitry.blogspot.in/2011/08/android-upload-progress.html
这篇关于安卓:更新进度条的文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!