Php 在写入期间取消HTTP Post文件上载到服务器-Android

Php 在写入期间取消HTTP Post文件上载到服务器-Android,php,android,file-upload,dialog,http-post,Php,Android,File Upload,Dialog,Http Post,我一直在发疯想弄明白这一点。我已经研究了一些可能的解决方案,包括,下面的5(,,)和更多,但似乎没有一个能很好地解决这个问题 我目前能做的事情: package com.example.<package_name>; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.List; import android.app.Activity; i

我一直在发疯想弄明白这一点。我已经研究了一些可能的解决方案,包括,下面的5(,,)和更多,但似乎没有一个能很好地解决这个问题

我目前能做的事情:

package com.example.<package_name>;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.example.<package_name>.ListenerList.FireHandler;
import com.example.<package_name>.utils.UploadToServer;

public class FileDialog extends Activity {
    public static boolean cancelled;
    private static final String PARENT_DIR = "..";
    private final String TAG = getClass().getName();
    private String[] fileList;
    private File currentPath;

    public interface FileSelectedListener {
        void fileSelected(File file);
    }

    public interface DirectorySelectedListener {
        void directorySelected(File directory);
    }

    private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
    private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
    private final Activity activity;
    private boolean selectDirectoryOption;
    private String fileEndsWith;

    /**
     * @param activity
     * @param initialPath
     */
    public FileDialog(Activity activity, File path) {
        this.activity = activity;
        if (!path.exists())
            path = Environment.getExternalStorageDirectory();
        loadFileList(path);
    }

    /**
     * @return file dialog
     */
    public Dialog createFileDialog() {
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.setTitle("Select a file to upload. Current path = "
                + currentPath.getPath());
        if (selectDirectoryOption) {
            builder.setPositiveButton("Select directory",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Log.d(TAG, currentPath.getPath());
                            fireDirectorySelectedEvent(currentPath);
                        }
                    });
        }

        builder.setItems(fileList, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String fileChosen = fileList[which];
                File chosenFile = getChosenFile(fileChosen);
                cancelled = true;
                if (chosenFile.isDirectory()) {
                    loadFileList(chosenFile);
                    dialog.cancel();
                    dialog.dismiss();
                    showDialog();
                } else {
                    Intent intent = new Intent(activity, UploadToServer.class);
                    Bundle fileInfo = new Bundle();
                    fileInfo.putString(
                            UploadToServer.UPLOAD_FILE_DIRECTORY_KEY,
                            currentPath.getPath());
                    fileInfo.putString(UploadToServer.UPLOAD_FILE_NAME_KEY,
                            chosenFile.getName());
                    intent.putExtras(fileInfo); // Pass the file info to the
                                                // UploadToServer activity
                    activity.startActivity(intent);
                    fireFileSelectedEvent(chosenFile);
                }
            }
        });

        dialog = builder.show();
        return dialog;
    }

    public void addFileListener(FileSelectedListener listener) {
        fileListenerList.add(listener);
    }

    public void removeFileListener(FileSelectedListener listener) {
        fileListenerList.remove(listener);
    }

    public void setSelectDirectoryOption(boolean selectDirectoryOption) {
        this.selectDirectoryOption = selectDirectoryOption;
    }

    public void addDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.add(listener);
    }

    public void removeDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.remove(listener);
    }

    /**
     * Show file dialog
     */
    public void showDialog() {
        createFileDialog().show();
    }

    private void fireFileSelectedEvent(final File file) {
        fileListenerList
                .fireEvent(new FireHandler<FileDialog.FileSelectedListener>() {
                    @Override
                    public void fireEvent(FileSelectedListener listener) {
                        listener.fileSelected(file);
                    }
                });
    }

    private void fireDirectorySelectedEvent(final File directory) {
        dirListenerList
                .fireEvent(new FireHandler<FileDialog.DirectorySelectedListener>() {
                    @Override
                    public void fireEvent(DirectorySelectedListener listener) {
                        listener.directorySelected(directory);
                    }
                });
    }

    private void loadFileList(File path) {
        this.currentPath = path;
        List<String> r = new ArrayList<String>();
        if (path.exists()) {
            if (path.getParentFile() != null)
                r.add(PARENT_DIR);
            FilenameFilter filter = new FilenameFilter() {
                @Override
                public boolean accept(File dir, String filename) {
                    File sel = new File(dir, filename);
                    if (!sel.canRead())
                        return false;
                    if (selectDirectoryOption)
                        return sel.isDirectory();
                    else {
                        boolean endsWith = fileEndsWith != null ? filename
                                .toLowerCase().endsWith(fileEndsWith) : true;
                        return endsWith || sel.isDirectory();
                    }
                }
            };
            String[] fileList1 = path.list(filter);
            for (String file : fileList1) {
                r.add(file);
            }
        }
        fileList = (String[]) r.toArray(new String[] {});
    }

    private File getChosenFile(String fileChosen) {
        if (fileChosen.equals(PARENT_DIR))
            return currentPath.getParentFile();
        else
            return new File(currentPath, fileChosen);
    }

    public void setFileEndsWith(String fileEndsWith) {
        this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase()
                : fileEndsWith;
    }
}

class ListenerList<L> {
    private List<L> listenerList = new ArrayList<L>();

    public interface FireHandler<L> {
        void fireEvent(L listener);
    }

    public void add(L listener) {
        listenerList.add(listener);
    }

    public void fireEvent(FireHandler<L> fireHandler) {
        List<L> copy = new ArrayList<L>(listenerList);
        for (L l : copy) {
            fireHandler.fireEvent(l);
        }
    }

    public void remove(L listener) {
        listenerList.remove(listener);
    }

    public List<L> getListenerList() {
        return listenerList;
    }
}
package com.example.<package_name>.utils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.<package_name>.FileDialog;
import com.example.<package_name>.R;

public class UploadToServer extends Activity {

    /**
     * The key for the upload file path value passed through the start-up
     * intent.
     */
    public static final String UPLOAD_FILE_DIRECTORY_KEY = "UploadToServer.uploadFileDirectory";
    /**
     * The key for the upload file name value passed through the start-up
     * intent.
     */
    public static final String UPLOAD_FILE_NAME_KEY = "UploadToServer.uploadFileName";

    TextView messageText;
    Button uploadButton;
    int serverResponseCode = 0;
    ProgressDialog dialog = null;

    String upLoadServerUri = null;

    private String uploadFileDirectory;
    private String uploadFileName;

    private FileUploadRunnable fileUploadRunnable;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_to_server);

        Bundle fileInfo = getIntent().getExtras();
        uploadFileDirectory = fileInfo.getString(UPLOAD_FILE_DIRECTORY_KEY);
        uploadFileName = fileInfo.getString(UPLOAD_FILE_NAME_KEY);

        messageText = (TextView) findViewById(R.id.messageText);

        messageText.setText("Uploading file path :- " + uploadFileDirectory
                + "/" + uploadFileName);

        /************* Php script path ****************/
        upLoadServerUri = "http://<server_ip>/UploadToServer.php";

        DialogInterface.OnCancelListener onCancelListener = new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        };

        dialog = ProgressDialog.show(UploadToServer.this, "",
                "Uploading file...", true, true, onCancelListener);

        messageText.setText("uploading started.....");

        fileUploadRunnable = new FileUploadRunnable(uploadFileDirectory,
                uploadFileName);

        new Thread(fileUploadRunnable).start();
    }

    @Override
    public void onBackPressed() {
        if (fileUploadRunnable != null) {
            fileUploadRunnable.cancelUpload();
        }
        super.onBackPressed();
    }

    private class FileUploadRunnable implements Runnable {

        private final String uploadFileDirectory;
        private final String uploadFileName;
        private HttpURLConnection conn;
        private final Object dosLock;
        private boolean doUpload;
        DataOutputStream dos;

        public FileUploadRunnable(String uploadFileDirectory,
                String uploadFileName) {
            this.uploadFileDirectory = uploadFileDirectory;
            this.uploadFileName = uploadFileName;
            conn = null;
            Lock = new Object();
            doUpload = true;
            dos = null;
        }

        @Override
        public void run() {
            uploadFile(uploadFileDirectory + "/" + uploadFileName);
        }

        /**
         * cancel the current upload
         */
        public void cancelUpload() {
            synchronized (dosLock) {
                if (dos != null) {
                    try {
                        dos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                doUpload = false;
            }
        }

        private void uploadFile(String sourceFileUri) {

            String fileName = sourceFileUri;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            File sourceFile = new File(sourceFileUri);

            if (!sourceFile.isFile()) {

                dialog.dismiss();

                Log.e("uploadFile", "Source File not exist :"
                        + uploadFileDirectory + uploadFileName);

                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("Source File not exist :"
                                + uploadFileDirectory + uploadFileName);
                    }
                });

                return;

            } else {
                try {
                    // open a URL connection to the Servlet
                    URL url = new URL(upLoadServerUri);

                    // Open a HTTP connection to the URL
                    conn = (HttpURLConnection) url.openConnection();
                    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);

                    synchronized (dosLock) {

                        if (!doUpload) {
                            return;
                        }

                        dos = new DataOutputStream(conn.getOutputStream());

                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                + fileName + "\"" + lineEnd);

                        dos.writeBytes(lineEnd);

                    } // end synchronization block

                    FileInputStream fileInputStream = new FileInputStream(
                            sourceFile);

                    // create a buffer of maximum size
                    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) {

                        synchronized (dosLock) {
                            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);

                    // Responses from the server (code and message)
                    serverResponseCode = conn.getResponseCode();
                    String serverResponseMessage = conn.getResponseMessage();

                    Log.i("uploadFile", "HTTP Response is : "
                            + serverResponseMessage + ": " + serverResponseCode);

                    if (serverResponseCode == 200) {

                        runOnUiThread(new Runnable() {
                            public void run() {

                                String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                        + " http://www.androidexample.com/media/uploads/"
                                        + uploadFileName;

                                messageText.setText(msg);
                                Toast.makeText(UploadToServer.this,
                                        "File Upload Complete.",
                                        Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    // close the streams //
                    fileInputStream.close();
                    dos.flush();
                    dos.close();

                } catch (MalformedURLException ex) {

                    dialog.dismiss();
                    ex.printStackTrace();

                    runOnUiThread(new Runnable() {
                        public void run() {
                            messageText
                                    .setText("MalformedURLException Exception : check script url.");
                            Toast.makeText(UploadToServer.this,
                                    "MalformedURLException", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });

                    Log.e("Upload file to server", "error: " + ex.getMessage(),
                            ex);
                } catch (IOException e) {
                    // TODO if doUpload is false here, then this is expected, so pop-up a toast.
                    // TODO if doUpload is true here, then this is NOT expected, so open an error dialog.

            } catch (Exception e) {
                // TODO this is for unexpected exceptions, so open an error dialog.

                    dialog.dismiss();
                    e.printStackTrace();

                    runOnUiThread(new Runnable() {
                        public void run() {
                            messageText.setText("Got Exception : see logcat ");
                            Toast.makeText(UploadToServer.this,
                                    "Got Exception : see logcat ",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                    Log.e("Upload file to server Exception",
                            "Exception : " + e.getMessage(), e);
                }
                dialog.dismiss();

            } // End else block
        }
    }
}
我目前拥有从主应用程序打开自定义文件对话框活动的功能。从这个对话框中,我选择要上载到服务器的特定文件。该服务器只是我本地机器上的一个Apache服务器,它与我运行应用程序的三星S4连接到同一个Wi-Fi网络。我可以选择要上载的文件,这将启动一个新活动并显示一个进度对话框。假设服务器、Wi-Fi和电话都已正确连接,文件将按预期上载。此文件上载过程使用HTTP Post请求

我想做什么:

package com.example.<package_name>;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.example.<package_name>.ListenerList.FireHandler;
import com.example.<package_name>.utils.UploadToServer;

public class FileDialog extends Activity {
    public static boolean cancelled;
    private static final String PARENT_DIR = "..";
    private final String TAG = getClass().getName();
    private String[] fileList;
    private File currentPath;

    public interface FileSelectedListener {
        void fileSelected(File file);
    }

    public interface DirectorySelectedListener {
        void directorySelected(File directory);
    }

    private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
    private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
    private final Activity activity;
    private boolean selectDirectoryOption;
    private String fileEndsWith;

    /**
     * @param activity
     * @param initialPath
     */
    public FileDialog(Activity activity, File path) {
        this.activity = activity;
        if (!path.exists())
            path = Environment.getExternalStorageDirectory();
        loadFileList(path);
    }

    /**
     * @return file dialog
     */
    public Dialog createFileDialog() {
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.setTitle("Select a file to upload. Current path = "
                + currentPath.getPath());
        if (selectDirectoryOption) {
            builder.setPositiveButton("Select directory",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Log.d(TAG, currentPath.getPath());
                            fireDirectorySelectedEvent(currentPath);
                        }
                    });
        }

        builder.setItems(fileList, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String fileChosen = fileList[which];
                File chosenFile = getChosenFile(fileChosen);
                cancelled = true;
                if (chosenFile.isDirectory()) {
                    loadFileList(chosenFile);
                    dialog.cancel();
                    dialog.dismiss();
                    showDialog();
                } else {
                    Intent intent = new Intent(activity, UploadToServer.class);
                    Bundle fileInfo = new Bundle();
                    fileInfo.putString(
                            UploadToServer.UPLOAD_FILE_DIRECTORY_KEY,
                            currentPath.getPath());
                    fileInfo.putString(UploadToServer.UPLOAD_FILE_NAME_KEY,
                            chosenFile.getName());
                    intent.putExtras(fileInfo); // Pass the file info to the
                                                // UploadToServer activity
                    activity.startActivity(intent);
                    fireFileSelectedEvent(chosenFile);
                }
            }
        });

        dialog = builder.show();
        return dialog;
    }

    public void addFileListener(FileSelectedListener listener) {
        fileListenerList.add(listener);
    }

    public void removeFileListener(FileSelectedListener listener) {
        fileListenerList.remove(listener);
    }

    public void setSelectDirectoryOption(boolean selectDirectoryOption) {
        this.selectDirectoryOption = selectDirectoryOption;
    }

    public void addDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.add(listener);
    }

    public void removeDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.remove(listener);
    }

    /**
     * Show file dialog
     */
    public void showDialog() {
        createFileDialog().show();
    }

    private void fireFileSelectedEvent(final File file) {
        fileListenerList
                .fireEvent(new FireHandler<FileDialog.FileSelectedListener>() {
                    @Override
                    public void fireEvent(FileSelectedListener listener) {
                        listener.fileSelected(file);
                    }
                });
    }

    private void fireDirectorySelectedEvent(final File directory) {
        dirListenerList
                .fireEvent(new FireHandler<FileDialog.DirectorySelectedListener>() {
                    @Override
                    public void fireEvent(DirectorySelectedListener listener) {
                        listener.directorySelected(directory);
                    }
                });
    }

    private void loadFileList(File path) {
        this.currentPath = path;
        List<String> r = new ArrayList<String>();
        if (path.exists()) {
            if (path.getParentFile() != null)
                r.add(PARENT_DIR);
            FilenameFilter filter = new FilenameFilter() {
                @Override
                public boolean accept(File dir, String filename) {
                    File sel = new File(dir, filename);
                    if (!sel.canRead())
                        return false;
                    if (selectDirectoryOption)
                        return sel.isDirectory();
                    else {
                        boolean endsWith = fileEndsWith != null ? filename
                                .toLowerCase().endsWith(fileEndsWith) : true;
                        return endsWith || sel.isDirectory();
                    }
                }
            };
            String[] fileList1 = path.list(filter);
            for (String file : fileList1) {
                r.add(file);
            }
        }
        fileList = (String[]) r.toArray(new String[] {});
    }

    private File getChosenFile(String fileChosen) {
        if (fileChosen.equals(PARENT_DIR))
            return currentPath.getParentFile();
        else
            return new File(currentPath, fileChosen);
    }

    public void setFileEndsWith(String fileEndsWith) {
        this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase()
                : fileEndsWith;
    }
}

class ListenerList<L> {
    private List<L> listenerList = new ArrayList<L>();

    public interface FireHandler<L> {
        void fireEvent(L listener);
    }

    public void add(L listener) {
        listenerList.add(listener);
    }

    public void fireEvent(FireHandler<L> fireHandler) {
        List<L> copy = new ArrayList<L>(listenerList);
        for (L l : copy) {
            fireHandler.fireEvent(l);
        }
    }

    public void remove(L listener) {
        listenerList.remove(listener);
    }

    public List<L> getListenerList() {
        return listenerList;
    }
}
package com.example.<package_name>.utils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.<package_name>.FileDialog;
import com.example.<package_name>.R;

public class UploadToServer extends Activity {

    /**
     * The key for the upload file path value passed through the start-up
     * intent.
     */
    public static final String UPLOAD_FILE_DIRECTORY_KEY = "UploadToServer.uploadFileDirectory";
    /**
     * The key for the upload file name value passed through the start-up
     * intent.
     */
    public static final String UPLOAD_FILE_NAME_KEY = "UploadToServer.uploadFileName";

    TextView messageText;
    Button uploadButton;
    int serverResponseCode = 0;
    ProgressDialog dialog = null;

    String upLoadServerUri = null;

    private String uploadFileDirectory;
    private String uploadFileName;

    private FileUploadRunnable fileUploadRunnable;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_to_server);

        Bundle fileInfo = getIntent().getExtras();
        uploadFileDirectory = fileInfo.getString(UPLOAD_FILE_DIRECTORY_KEY);
        uploadFileName = fileInfo.getString(UPLOAD_FILE_NAME_KEY);

        messageText = (TextView) findViewById(R.id.messageText);

        messageText.setText("Uploading file path :- " + uploadFileDirectory
                + "/" + uploadFileName);

        /************* Php script path ****************/
        upLoadServerUri = "http://<server_ip>/UploadToServer.php";

        DialogInterface.OnCancelListener onCancelListener = new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        };

        dialog = ProgressDialog.show(UploadToServer.this, "",
                "Uploading file...", true, true, onCancelListener);

        messageText.setText("uploading started.....");

        fileUploadRunnable = new FileUploadRunnable(uploadFileDirectory,
                uploadFileName);

        new Thread(fileUploadRunnable).start();
    }

    @Override
    public void onBackPressed() {
        if (fileUploadRunnable != null) {
            fileUploadRunnable.cancelUpload();
        }
        super.onBackPressed();
    }

    private class FileUploadRunnable implements Runnable {

        private final String uploadFileDirectory;
        private final String uploadFileName;
        private HttpURLConnection conn;
        private final Object dosLock;
        private boolean doUpload;
        DataOutputStream dos;

        public FileUploadRunnable(String uploadFileDirectory,
                String uploadFileName) {
            this.uploadFileDirectory = uploadFileDirectory;
            this.uploadFileName = uploadFileName;
            conn = null;
            Lock = new Object();
            doUpload = true;
            dos = null;
        }

        @Override
        public void run() {
            uploadFile(uploadFileDirectory + "/" + uploadFileName);
        }

        /**
         * cancel the current upload
         */
        public void cancelUpload() {
            synchronized (dosLock) {
                if (dos != null) {
                    try {
                        dos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                doUpload = false;
            }
        }

        private void uploadFile(String sourceFileUri) {

            String fileName = sourceFileUri;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            File sourceFile = new File(sourceFileUri);

            if (!sourceFile.isFile()) {

                dialog.dismiss();

                Log.e("uploadFile", "Source File not exist :"
                        + uploadFileDirectory + uploadFileName);

                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("Source File not exist :"
                                + uploadFileDirectory + uploadFileName);
                    }
                });

                return;

            } else {
                try {
                    // open a URL connection to the Servlet
                    URL url = new URL(upLoadServerUri);

                    // Open a HTTP connection to the URL
                    conn = (HttpURLConnection) url.openConnection();
                    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);

                    synchronized (dosLock) {

                        if (!doUpload) {
                            return;
                        }

                        dos = new DataOutputStream(conn.getOutputStream());

                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                + fileName + "\"" + lineEnd);

                        dos.writeBytes(lineEnd);

                    } // end synchronization block

                    FileInputStream fileInputStream = new FileInputStream(
                            sourceFile);

                    // create a buffer of maximum size
                    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) {

                        synchronized (dosLock) {
                            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);

                    // Responses from the server (code and message)
                    serverResponseCode = conn.getResponseCode();
                    String serverResponseMessage = conn.getResponseMessage();

                    Log.i("uploadFile", "HTTP Response is : "
                            + serverResponseMessage + ": " + serverResponseCode);

                    if (serverResponseCode == 200) {

                        runOnUiThread(new Runnable() {
                            public void run() {

                                String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                        + " http://www.androidexample.com/media/uploads/"
                                        + uploadFileName;

                                messageText.setText(msg);
                                Toast.makeText(UploadToServer.this,
                                        "File Upload Complete.",
                                        Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    // close the streams //
                    fileInputStream.close();
                    dos.flush();
                    dos.close();

                } catch (MalformedURLException ex) {

                    dialog.dismiss();
                    ex.printStackTrace();

                    runOnUiThread(new Runnable() {
                        public void run() {
                            messageText
                                    .setText("MalformedURLException Exception : check script url.");
                            Toast.makeText(UploadToServer.this,
                                    "MalformedURLException", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });

                    Log.e("Upload file to server", "error: " + ex.getMessage(),
                            ex);
                } catch (IOException e) {
                    // TODO if doUpload is false here, then this is expected, so pop-up a toast.
                    // TODO if doUpload is true here, then this is NOT expected, so open an error dialog.

            } catch (Exception e) {
                // TODO this is for unexpected exceptions, so open an error dialog.

                    dialog.dismiss();
                    e.printStackTrace();

                    runOnUiThread(new Runnable() {
                        public void run() {
                            messageText.setText("Got Exception : see logcat ");
                            Toast.makeText(UploadToServer.this,
                                    "Got Exception : see logcat ",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                    Log.e("Upload file to server Exception",
                            "Exception : " + e.getMessage(), e);
                }
                dialog.dismiss();

            } // End else block
        }
    }
}
<>我希望能够在任何时候取消文件上传,但特别是在将文件写入服务器的过程中。这是由三个主要场景引起的:1)如果文件很大,需要花费很长时间才能上载,并且用户希望停止上载,返回到“文件”对话框,然后选择其他文件进行上载;2)如果用户选择了错误的文件,并希望返回到“文件”对话框以选择正确的文件;3)如果服务器连接不正确,HTTP post正在挂起,用户希望停止文件上载,然后在所有内容正确连接后返回

到目前为止我所尝试的:

package com.example.<package_name>;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.example.<package_name>.ListenerList.FireHandler;
import com.example.<package_name>.utils.UploadToServer;

public class FileDialog extends Activity {
    public static boolean cancelled;
    private static final String PARENT_DIR = "..";
    private final String TAG = getClass().getName();
    private String[] fileList;
    private File currentPath;

    public interface FileSelectedListener {
        void fileSelected(File file);
    }

    public interface DirectorySelectedListener {
        void directorySelected(File directory);
    }

    private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
    private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
    private final Activity activity;
    private boolean selectDirectoryOption;
    private String fileEndsWith;

    /**
     * @param activity
     * @param initialPath
     */
    public FileDialog(Activity activity, File path) {
        this.activity = activity;
        if (!path.exists())
            path = Environment.getExternalStorageDirectory();
        loadFileList(path);
    }

    /**
     * @return file dialog
     */
    public Dialog createFileDialog() {
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.setTitle("Select a file to upload. Current path = "
                + currentPath.getPath());
        if (selectDirectoryOption) {
            builder.setPositiveButton("Select directory",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Log.d(TAG, currentPath.getPath());
                            fireDirectorySelectedEvent(currentPath);
                        }
                    });
        }

        builder.setItems(fileList, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String fileChosen = fileList[which];
                File chosenFile = getChosenFile(fileChosen);
                cancelled = true;
                if (chosenFile.isDirectory()) {
                    loadFileList(chosenFile);
                    dialog.cancel();
                    dialog.dismiss();
                    showDialog();
                } else {
                    Intent intent = new Intent(activity, UploadToServer.class);
                    Bundle fileInfo = new Bundle();
                    fileInfo.putString(
                            UploadToServer.UPLOAD_FILE_DIRECTORY_KEY,
                            currentPath.getPath());
                    fileInfo.putString(UploadToServer.UPLOAD_FILE_NAME_KEY,
                            chosenFile.getName());
                    intent.putExtras(fileInfo); // Pass the file info to the
                                                // UploadToServer activity
                    activity.startActivity(intent);
                    fireFileSelectedEvent(chosenFile);
                }
            }
        });

        dialog = builder.show();
        return dialog;
    }

    public void addFileListener(FileSelectedListener listener) {
        fileListenerList.add(listener);
    }

    public void removeFileListener(FileSelectedListener listener) {
        fileListenerList.remove(listener);
    }

    public void setSelectDirectoryOption(boolean selectDirectoryOption) {
        this.selectDirectoryOption = selectDirectoryOption;
    }

    public void addDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.add(listener);
    }

    public void removeDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.remove(listener);
    }

    /**
     * Show file dialog
     */
    public void showDialog() {
        createFileDialog().show();
    }

    private void fireFileSelectedEvent(final File file) {
        fileListenerList
                .fireEvent(new FireHandler<FileDialog.FileSelectedListener>() {
                    @Override
                    public void fireEvent(FileSelectedListener listener) {
                        listener.fileSelected(file);
                    }
                });
    }

    private void fireDirectorySelectedEvent(final File directory) {
        dirListenerList
                .fireEvent(new FireHandler<FileDialog.DirectorySelectedListener>() {
                    @Override
                    public void fireEvent(DirectorySelectedListener listener) {
                        listener.directorySelected(directory);
                    }
                });
    }

    private void loadFileList(File path) {
        this.currentPath = path;
        List<String> r = new ArrayList<String>();
        if (path.exists()) {
            if (path.getParentFile() != null)
                r.add(PARENT_DIR);
            FilenameFilter filter = new FilenameFilter() {
                @Override
                public boolean accept(File dir, String filename) {
                    File sel = new File(dir, filename);
                    if (!sel.canRead())
                        return false;
                    if (selectDirectoryOption)
                        return sel.isDirectory();
                    else {
                        boolean endsWith = fileEndsWith != null ? filename
                                .toLowerCase().endsWith(fileEndsWith) : true;
                        return endsWith || sel.isDirectory();
                    }
                }
            };
            String[] fileList1 = path.list(filter);
            for (String file : fileList1) {
                r.add(file);
            }
        }
        fileList = (String[]) r.toArray(new String[] {});
    }

    private File getChosenFile(String fileChosen) {
        if (fileChosen.equals(PARENT_DIR))
            return currentPath.getParentFile();
        else
            return new File(currentPath, fileChosen);
    }

    public void setFileEndsWith(String fileEndsWith) {
        this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase()
                : fileEndsWith;
    }
}

class ListenerList<L> {
    private List<L> listenerList = new ArrayList<L>();

    public interface FireHandler<L> {
        void fireEvent(L listener);
    }

    public void add(L listener) {
        listenerList.add(listener);
    }

    public void fireEvent(FireHandler<L> fireHandler) {
        List<L> copy = new ArrayList<L>(listenerList);
        for (L l : copy) {
            fireHandler.fireEvent(l);
        }
    }

    public void remove(L listener) {
        listenerList.remove(listener);
    }

    public List<L> getListenerList() {
        return listenerList;
    }
}
package com.example.<package_name>.utils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.<package_name>.FileDialog;
import com.example.<package_name>.R;

public class UploadToServer extends Activity {

    /**
     * The key for the upload file path value passed through the start-up
     * intent.
     */
    public static final String UPLOAD_FILE_DIRECTORY_KEY = "UploadToServer.uploadFileDirectory";
    /**
     * The key for the upload file name value passed through the start-up
     * intent.
     */
    public static final String UPLOAD_FILE_NAME_KEY = "UploadToServer.uploadFileName";

    TextView messageText;
    Button uploadButton;
    int serverResponseCode = 0;
    ProgressDialog dialog = null;

    String upLoadServerUri = null;

    private String uploadFileDirectory;
    private String uploadFileName;

    private FileUploadRunnable fileUploadRunnable;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_to_server);

        Bundle fileInfo = getIntent().getExtras();
        uploadFileDirectory = fileInfo.getString(UPLOAD_FILE_DIRECTORY_KEY);
        uploadFileName = fileInfo.getString(UPLOAD_FILE_NAME_KEY);

        messageText = (TextView) findViewById(R.id.messageText);

        messageText.setText("Uploading file path :- " + uploadFileDirectory
                + "/" + uploadFileName);

        /************* Php script path ****************/
        upLoadServerUri = "http://<server_ip>/UploadToServer.php";

        DialogInterface.OnCancelListener onCancelListener = new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        };

        dialog = ProgressDialog.show(UploadToServer.this, "",
                "Uploading file...", true, true, onCancelListener);

        messageText.setText("uploading started.....");

        fileUploadRunnable = new FileUploadRunnable(uploadFileDirectory,
                uploadFileName);

        new Thread(fileUploadRunnable).start();
    }

    @Override
    public void onBackPressed() {
        if (fileUploadRunnable != null) {
            fileUploadRunnable.cancelUpload();
        }
        super.onBackPressed();
    }

    private class FileUploadRunnable implements Runnable {

        private final String uploadFileDirectory;
        private final String uploadFileName;
        private HttpURLConnection conn;
        private final Object dosLock;
        private boolean doUpload;
        DataOutputStream dos;

        public FileUploadRunnable(String uploadFileDirectory,
                String uploadFileName) {
            this.uploadFileDirectory = uploadFileDirectory;
            this.uploadFileName = uploadFileName;
            conn = null;
            Lock = new Object();
            doUpload = true;
            dos = null;
        }

        @Override
        public void run() {
            uploadFile(uploadFileDirectory + "/" + uploadFileName);
        }

        /**
         * cancel the current upload
         */
        public void cancelUpload() {
            synchronized (dosLock) {
                if (dos != null) {
                    try {
                        dos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                doUpload = false;
            }
        }

        private void uploadFile(String sourceFileUri) {

            String fileName = sourceFileUri;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            File sourceFile = new File(sourceFileUri);

            if (!sourceFile.isFile()) {

                dialog.dismiss();

                Log.e("uploadFile", "Source File not exist :"
                        + uploadFileDirectory + uploadFileName);

                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("Source File not exist :"
                                + uploadFileDirectory + uploadFileName);
                    }
                });

                return;

            } else {
                try {
                    // open a URL connection to the Servlet
                    URL url = new URL(upLoadServerUri);

                    // Open a HTTP connection to the URL
                    conn = (HttpURLConnection) url.openConnection();
                    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);

                    synchronized (dosLock) {

                        if (!doUpload) {
                            return;
                        }

                        dos = new DataOutputStream(conn.getOutputStream());

                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                + fileName + "\"" + lineEnd);

                        dos.writeBytes(lineEnd);

                    } // end synchronization block

                    FileInputStream fileInputStream = new FileInputStream(
                            sourceFile);

                    // create a buffer of maximum size
                    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) {

                        synchronized (dosLock) {
                            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);

                    // Responses from the server (code and message)
                    serverResponseCode = conn.getResponseCode();
                    String serverResponseMessage = conn.getResponseMessage();

                    Log.i("uploadFile", "HTTP Response is : "
                            + serverResponseMessage + ": " + serverResponseCode);

                    if (serverResponseCode == 200) {

                        runOnUiThread(new Runnable() {
                            public void run() {

                                String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                        + " http://www.androidexample.com/media/uploads/"
                                        + uploadFileName;

                                messageText.setText(msg);
                                Toast.makeText(UploadToServer.this,
                                        "File Upload Complete.",
                                        Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    // close the streams //
                    fileInputStream.close();
                    dos.flush();
                    dos.close();

                } catch (MalformedURLException ex) {

                    dialog.dismiss();
                    ex.printStackTrace();

                    runOnUiThread(new Runnable() {
                        public void run() {
                            messageText
                                    .setText("MalformedURLException Exception : check script url.");
                            Toast.makeText(UploadToServer.this,
                                    "MalformedURLException", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });

                    Log.e("Upload file to server", "error: " + ex.getMessage(),
                            ex);
                } catch (IOException e) {
                    // TODO if doUpload is false here, then this is expected, so pop-up a toast.
                    // TODO if doUpload is true here, then this is NOT expected, so open an error dialog.

            } catch (Exception e) {
                // TODO this is for unexpected exceptions, so open an error dialog.

                    dialog.dismiss();
                    e.printStackTrace();

                    runOnUiThread(new Runnable() {
                        public void run() {
                            messageText.setText("Got Exception : see logcat ");
                            Toast.makeText(UploadToServer.this,
                                    "Got Exception : see logcat ",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                    Log.e("Upload file to server Exception",
                            "Exception : " + e.getMessage(), e);
                }
                dialog.dismiss();

            } // End else block
        }
    }
}
我尝试的第一件事是简单地使“进度”对话框可取消,如下所示:

DialogInterface.OnCancelListener onCancelListener = new DialogInterface.OnCancelListener() {

@Override
public void onCancel(DialogInterface dialog) {
    finish();
    }
};

dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true, true, onCancelListener);
然而,这仍然允许上传完成

我尝试的第二件事是简单地中断文件上传线程(使用thread.interrupt),但文件上传仍然完成

我尝试的第三件事是断开HttpURLConnection。我在同步相关代码块和不同步相关代码块的情况下尝试了这一点,但文件上传仍然完成。将抛出一个异常,表示套接字已关闭,但直到它尝试获取服务器响应代码时才抛出,而不是像我所期望的那样在它开始编写时立即抛出

我尝试的第四件(也是主要的)事情是在按下后退按钮时关闭DataOutputStream。我在同步相关代码块和不同步相关代码块的情况下尝试了这一点,但文件上传仍然完成。但是,如果我在开始写入服务器上的缓冲区之前关闭DataOutputStream,则该流将关闭,我将获得一个IOException,并且文件上载将成功取消。我似乎不知道如何在数据开始写入服务器后取消文件上载

在其他关于SO的帖子中,人们建议使用finish()、System.exit(0)、android.os.Process.killProcess(android.os.Process.myPid())、HttpClient、AsyncTask和其他很多东西,但它们似乎都不是我想要的,除了AsyncTask,尽管我仍然不相信这就是我想要的

我想做的事可能吗?我有一种感觉可能不是

我希望我的问题足够清楚和具体。如果没有,请让我知道我可以澄清什么,我遗漏了什么,什么是完全没有意义的=P

文件对话框代码:

package com.example.<package_name>;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.example.<package_name>.ListenerList.FireHandler;
import com.example.<package_name>.utils.UploadToServer;

public class FileDialog extends Activity {
    public static boolean cancelled;
    private static final String PARENT_DIR = "..";
    private final String TAG = getClass().getName();
    private String[] fileList;
    private File currentPath;

    public interface FileSelectedListener {
        void fileSelected(File file);
    }

    public interface DirectorySelectedListener {
        void directorySelected(File directory);
    }

    private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
    private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
    private final Activity activity;
    private boolean selectDirectoryOption;
    private String fileEndsWith;

    /**
     * @param activity
     * @param initialPath
     */
    public FileDialog(Activity activity, File path) {
        this.activity = activity;
        if (!path.exists())
            path = Environment.getExternalStorageDirectory();
        loadFileList(path);
    }

    /**
     * @return file dialog
     */
    public Dialog createFileDialog() {
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.setTitle("Select a file to upload. Current path = "
                + currentPath.getPath());
        if (selectDirectoryOption) {
            builder.setPositiveButton("Select directory",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Log.d(TAG, currentPath.getPath());
                            fireDirectorySelectedEvent(currentPath);
                        }
                    });
        }

        builder.setItems(fileList, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String fileChosen = fileList[which];
                File chosenFile = getChosenFile(fileChosen);
                cancelled = true;
                if (chosenFile.isDirectory()) {
                    loadFileList(chosenFile);
                    dialog.cancel();
                    dialog.dismiss();
                    showDialog();
                } else {
                    Intent intent = new Intent(activity, UploadToServer.class);
                    Bundle fileInfo = new Bundle();
                    fileInfo.putString(
                            UploadToServer.UPLOAD_FILE_DIRECTORY_KEY,
                            currentPath.getPath());
                    fileInfo.putString(UploadToServer.UPLOAD_FILE_NAME_KEY,
                            chosenFile.getName());
                    intent.putExtras(fileInfo); // Pass the file info to the
                                                // UploadToServer activity
                    activity.startActivity(intent);
                    fireFileSelectedEvent(chosenFile);
                }
            }
        });

        dialog = builder.show();
        return dialog;
    }

    public void addFileListener(FileSelectedListener listener) {
        fileListenerList.add(listener);
    }

    public void removeFileListener(FileSelectedListener listener) {
        fileListenerList.remove(listener);
    }

    public void setSelectDirectoryOption(boolean selectDirectoryOption) {
        this.selectDirectoryOption = selectDirectoryOption;
    }

    public void addDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.add(listener);
    }

    public void removeDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.remove(listener);
    }

    /**
     * Show file dialog
     */
    public void showDialog() {
        createFileDialog().show();
    }

    private void fireFileSelectedEvent(final File file) {
        fileListenerList
                .fireEvent(new FireHandler<FileDialog.FileSelectedListener>() {
                    @Override
                    public void fireEvent(FileSelectedListener listener) {
                        listener.fileSelected(file);
                    }
                });
    }

    private void fireDirectorySelectedEvent(final File directory) {
        dirListenerList
                .fireEvent(new FireHandler<FileDialog.DirectorySelectedListener>() {
                    @Override
                    public void fireEvent(DirectorySelectedListener listener) {
                        listener.directorySelected(directory);
                    }
                });
    }

    private void loadFileList(File path) {
        this.currentPath = path;
        List<String> r = new ArrayList<String>();
        if (path.exists()) {
            if (path.getParentFile() != null)
                r.add(PARENT_DIR);
            FilenameFilter filter = new FilenameFilter() {
                @Override
                public boolean accept(File dir, String filename) {
                    File sel = new File(dir, filename);
                    if (!sel.canRead())
                        return false;
                    if (selectDirectoryOption)
                        return sel.isDirectory();
                    else {
                        boolean endsWith = fileEndsWith != null ? filename
                                .toLowerCase().endsWith(fileEndsWith) : true;
                        return endsWith || sel.isDirectory();
                    }
                }
            };
            String[] fileList1 = path.list(filter);
            for (String file : fileList1) {
                r.add(file);
            }
        }
        fileList = (String[]) r.toArray(new String[] {});
    }

    private File getChosenFile(String fileChosen) {
        if (fileChosen.equals(PARENT_DIR))
            return currentPath.getParentFile();
        else
            return new File(currentPath, fileChosen);
    }

    public void setFileEndsWith(String fileEndsWith) {
        this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase()
                : fileEndsWith;
    }
}

class ListenerList<L> {
    private List<L> listenerList = new ArrayList<L>();

    public interface FireHandler<L> {
        void fireEvent(L listener);
    }

    public void add(L listener) {
        listenerList.add(listener);
    }

    public void fireEvent(FireHandler<L> fireHandler) {
        List<L> copy = new ArrayList<L>(listenerList);
        for (L l : copy) {
            fireHandler.fireEvent(l);
        }
    }

    public void remove(L listener) {
        listenerList.remove(listener);
    }

    public List<L> getListenerList() {
        return listenerList;
    }
}
package com.example.<package_name>.utils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.<package_name>.FileDialog;
import com.example.<package_name>.R;

public class UploadToServer extends Activity {

    /**
     * The key for the upload file path value passed through the start-up
     * intent.
     */
    public static final String UPLOAD_FILE_DIRECTORY_KEY = "UploadToServer.uploadFileDirectory";
    /**
     * The key for the upload file name value passed through the start-up
     * intent.
     */
    public static final String UPLOAD_FILE_NAME_KEY = "UploadToServer.uploadFileName";

    TextView messageText;
    Button uploadButton;
    int serverResponseCode = 0;
    ProgressDialog dialog = null;

    String upLoadServerUri = null;

    private String uploadFileDirectory;
    private String uploadFileName;

    private FileUploadRunnable fileUploadRunnable;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_to_server);

        Bundle fileInfo = getIntent().getExtras();
        uploadFileDirectory = fileInfo.getString(UPLOAD_FILE_DIRECTORY_KEY);
        uploadFileName = fileInfo.getString(UPLOAD_FILE_NAME_KEY);

        messageText = (TextView) findViewById(R.id.messageText);

        messageText.setText("Uploading file path :- " + uploadFileDirectory
                + "/" + uploadFileName);

        /************* Php script path ****************/
        upLoadServerUri = "http://<server_ip>/UploadToServer.php";

        DialogInterface.OnCancelListener onCancelListener = new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        };

        dialog = ProgressDialog.show(UploadToServer.this, "",
                "Uploading file...", true, true, onCancelListener);

        messageText.setText("uploading started.....");

        fileUploadRunnable = new FileUploadRunnable(uploadFileDirectory,
                uploadFileName);

        new Thread(fileUploadRunnable).start();
    }

    @Override
    public void onBackPressed() {
        if (fileUploadRunnable != null) {
            fileUploadRunnable.cancelUpload();
        }
        super.onBackPressed();
    }

    private class FileUploadRunnable implements Runnable {

        private final String uploadFileDirectory;
        private final String uploadFileName;
        private HttpURLConnection conn;
        private final Object dosLock;
        private boolean doUpload;
        DataOutputStream dos;

        public FileUploadRunnable(String uploadFileDirectory,
                String uploadFileName) {
            this.uploadFileDirectory = uploadFileDirectory;
            this.uploadFileName = uploadFileName;
            conn = null;
            Lock = new Object();
            doUpload = true;
            dos = null;
        }

        @Override
        public void run() {
            uploadFile(uploadFileDirectory + "/" + uploadFileName);
        }

        /**
         * cancel the current upload
         */
        public void cancelUpload() {
            synchronized (dosLock) {
                if (dos != null) {
                    try {
                        dos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                doUpload = false;
            }
        }

        private void uploadFile(String sourceFileUri) {

            String fileName = sourceFileUri;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            File sourceFile = new File(sourceFileUri);

            if (!sourceFile.isFile()) {

                dialog.dismiss();

                Log.e("uploadFile", "Source File not exist :"
                        + uploadFileDirectory + uploadFileName);

                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("Source File not exist :"
                                + uploadFileDirectory + uploadFileName);
                    }
                });

                return;

            } else {
                try {
                    // open a URL connection to the Servlet
                    URL url = new URL(upLoadServerUri);

                    // Open a HTTP connection to the URL
                    conn = (HttpURLConnection) url.openConnection();
                    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);

                    synchronized (dosLock) {

                        if (!doUpload) {
                            return;
                        }

                        dos = new DataOutputStream(conn.getOutputStream());

                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                + fileName + "\"" + lineEnd);

                        dos.writeBytes(lineEnd);

                    } // end synchronization block

                    FileInputStream fileInputStream = new FileInputStream(
                            sourceFile);

                    // create a buffer of maximum size
                    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) {

                        synchronized (dosLock) {
                            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);

                    // Responses from the server (code and message)
                    serverResponseCode = conn.getResponseCode();
                    String serverResponseMessage = conn.getResponseMessage();

                    Log.i("uploadFile", "HTTP Response is : "
                            + serverResponseMessage + ": " + serverResponseCode);

                    if (serverResponseCode == 200) {

                        runOnUiThread(new Runnable() {
                            public void run() {

                                String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                        + " http://www.androidexample.com/media/uploads/"
                                        + uploadFileName;

                                messageText.setText(msg);
                                Toast.makeText(UploadToServer.this,
                                        "File Upload Complete.",
                                        Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    // close the streams //
                    fileInputStream.close();
                    dos.flush();
                    dos.close();

                } catch (MalformedURLException ex) {

                    dialog.dismiss();
                    ex.printStackTrace();

                    runOnUiThread(new Runnable() {
                        public void run() {
                            messageText
                                    .setText("MalformedURLException Exception : check script url.");
                            Toast.makeText(UploadToServer.this,
                                    "MalformedURLException", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });

                    Log.e("Upload file to server", "error: " + ex.getMessage(),
                            ex);
                } catch (IOException e) {
                    // TODO if doUpload is false here, then this is expected, so pop-up a toast.
                    // TODO if doUpload is true here, then this is NOT expected, so open an error dialog.

            } catch (Exception e) {
                // TODO this is for unexpected exceptions, so open an error dialog.

                    dialog.dismiss();
                    e.printStackTrace();

                    runOnUiThread(new Runnable() {
                        public void run() {
                            messageText.setText("Got Exception : see logcat ");
                            Toast.makeText(UploadToServer.this,
                                    "Got Exception : see logcat ",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                    Log.e("Upload file to server Exception",
                            "Exception : " + e.getMessage(), e);
                }
                dialog.dismiss();

            } // End else block
        }
    }
}
package.com.example。;
导入java.io.File;
导入java.io.FilenameFilter;
导入java.util.ArrayList;
导入java.util.List;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.app.Dialog;
导入android.content.DialogInterface;
导入android.content.Intent;
导入android.os.Bundle;
导入android.os.Environment;
导入android.util.Log;
导入com.example..ListenerList.FireHandler;
导入com.example..utils.UploadToServer;
公共类FileDialog扩展活动{
取消公共静态布尔值;
私有静态最终字符串PARENT_DIR=“…”;
私有最终字符串标记=getClass().getName();
私有字符串[]文件列表;
私有文件路径;
公共接口文件SelectedListener{
选择的无效文件(文件);
}
公共接口目录SelectedListener{
已选择无效目录(文件目录);
}
私有ListenerList fileListenerList=新建ListenerList();
私有ListenerList dirListenerList=新建ListenerList();
私人最终活动;
私有布尔selectDirectoryOption;
私有字符串fileEndsWith;
/**
*@param活动
*@param initialPath
*/
公共文件对话框(活动、文件路径){
这个。活动=活动;
如果(!path.exists())
path=Environment.getExternalStorageDirectory();
加载文件列表(路径);
}
/**
*@返回文件对话框
*/
公共对话框createFileDialog(){
Dialog=null;
AlertDialog.Builder=新建AlertDialog.Builder(活动);
setTitle(“选择要上载的文件。当前路径=”
+currentPath.getPath());
如果(选择目录选项){
setPositiveButton(“选择目录”,
新建DialogInterface.OnClickListener(){
@凌驾
public void onClick(DialogInterface dialog,int which){
Log.d(标记,currentPath.getPath());
fireDirectorySelectedEvent(当前路径);
}
});
}
setItems(文件列表,新的DialogInterface.OnClickListener(){
@凌驾
public void onClick(DialogInterface dialog,int which){
字符串fileselected=fileList[which];
File chosenFile=getChosenFile(fileselected);
取消=真;
if(chosenFile.isDirectory()){
加载文件列表(已选择)