我想上传图像到我的服务器。因此,我已经构建了这个并发送到服务器效果很好。然而缺少一件事,那就是ProgressDialog
。我尝试了很多方法,但不知道如何以正确的方式做到这一点。目前,我在 preExecute 方法中的AsyncTask
中调用ImageUploader.uploadFile()
。
与doInBackground
一样,我必须发送一封电子邮件,其中包含照片作为附件。因此,照片需要先上传,然后才能附加到电子邮件中。那么如何做到这一点以及如何显示ProgressDialog
呢?
这就是我调用函数的方式:
@Override
protected void onPreExecute(){
super.onPreExecute();
if(isPhotoTaken()){
ImageUploader.uploadFile(getPhotoPath(), "http://www.example.com/upload.php", Step4.this);
}
}
这是我的图片上传器类
public class ImageUploader {
private static String serverResponseMessage = "";
private static int serverResponseCode = 0;
private static ProgressDialog dialog;
public static int uploadFile(final String sourceFileUri, final String serverFile, final Context context) {
Debug.out("SourceFileUri: " + sourceFileUri);
Debug.out("ServerFile: " + serverFile);
Thread thread = new Thread() {
@Override
public void run() {
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
dialog = new ProgressDialog(context);
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Uploading Image... Please wait!");
dialog.show();
}
});
String upLoadServerUri = serverFile;
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File Does not exist");
}
try { // open a URL connection to the Servlet
Debug.out("in the try");
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a
// HTTP
// connection
// to
// the
// URL
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
Debug.out("Set Properties and Datastream");
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name="uploaded_file";filename=""
+ fileName + """ + lineEnd);
dos.writeBytes(lineEnd);
Debug.out("Writes data");
bytesAvailable = fileInputStream.available(); // create a
// buffer of
// maximum
// size
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
Debug.out("Buffer done");
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Debug.out("Read Bytes");
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
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);
Debug.out("After sendData");
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
serverResponseMessage = conn.getResponseMessage();
Debug.out("Server Response: " + serverResponseCode);
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
Debug.out("HTTP Response is : " + serverResponseMessage
+ ": " + serverResponseCode);
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex) {
ex.printStackTrace();
// Toast.makeText(UploadImageDemo.this,
// "MalformedURLException", Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(),
ex);
} catch (Exception e) {
e.printStackTrace();
// Toast.makeText(UploadImageDemo.this, "Exception : " +
// e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
}
};
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Debug.out("Message: " + serverResponseMessage.toString());
return serverResponseCode;
}
}
评论:"@Tarsem我想在上传图像时显示进度对话框。因此,当ImageUploader中的线程处于活动状态时。
尝试以下分配:
class imageupload extends AsyncTask<Void, Void, Void> {
Dialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(context, "Uploading Image","Please Wait...");
}
@Override
protected Void doInBackground(Void... params) {
// Upload Image HERE
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialog.dismiss();
// You can Call another AsynTask here (achieve sending email work here)
}
}
您可以在预执行中显示进度对话框,在doInBackground中上传图像和发送电子邮件,并在postExectue中隐藏进度对话框。
在预执行中上传图像与异步任务的用途相反......如果您在doInBackground中执行上传,则不需要额外的线程。(这就是AsyncTask为你处理的)
或者您可以上传图片,然后(在执行后)启动另一个发送电子邮件的任务,尽管我不明白为什么您需要异步执行此操作?您也可以只发送发送电子邮件的意图...?
只需按以下方式使用 AsyncTask
。在你的主课上,ProgressDialog
的Object
。
private class UploadTask extends AsyncTask<Void, Void, Integer > {
@Override
protected void onPreExecute(){
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.show();
}
protected Integer doInBackground(URL... urls) {
if(isPhotoTaken()){
ImageUploader.uploadFile(getPhotoPath(), "http://www.example.com/upload.php",Step4.this);
}
return null;
}
protected void onPostExecute(Integer result) {
pd.dismiss();
}
}
异步任务自带四种方法onPreExecute()
doInBackground()
onPostExecute()
和onUpdateProgress()
,你只需要适当地实现方法即可。
您在onPreExecute()
进行上传和发送电子邮件doInBackground()
更新中显示进度onUpdateProgress()
隐藏onPostExecute()
进度。
编辑
一旦你做对了,你就不再需要线程了,因为 AsyncTask 的主要思想是创建一个单独的线程/进程并更新在 UI 线程上运行的 UI,onPreExecute()
onUpdateProgress()
onPostExecute()
doInBackground()
触发一个新线程,并且可以通过从其中调用 publishUpdate 来更新 UI,这反过来又会自动调用onUpdateProgress()