联网上传文件操作

来源:互联网 发布:java 热部署 编辑:程序博客网 时间:2024/06/07 10:53

上一篇我们讲了okhttputils的联网请求的操作,这篇文章我们介绍下 “文件(图片)上传”的操作:(对于初学者最好是把上一篇的联网请求看过再研究这篇,更容易理解)

APP的操作中经常会遇到一些文件,附件, 图片(单张/多张) 上传的情况,那么对于以下Android初学者来说,或许有些难度(我初学时也这样),那么我们就基于上一篇 “okhttputils 的联网请求”,来继续对okhttputils的 文件上传进行介绍。

最近的项目中有一个整体的工具类,我们先看下,然后再单个了解:

/** * 上传文件  工具类 */public class UploadFilesUtil {    /**     * 文件(图片)上传     *     * @param filePath 手机上传文件的地址     * @param callback     */    public static void upLoadFile(String filePath, StringCallback callback) {        File file;        if (filePath == null) {            ToastUtils.showToast("文件不存在");            return;        }        Bitmap smallBitmap = CompressImgUtil.compressImg(filePath);//压缩图片        file = CompressImgUtil.saveBitmapFile(smallBitmap);//Bitmap对象保存为图片文件        OkHttpUtils.post()                .url(NetUtils.URL_UPLOADE_FILE)                .addFile("file1", file.getName(), file)                .build()                .execute(callback);    }    /**     * 文件(图片)上传     *     * @param filePath 手机上传文件的地址     * @param callback     */    public static void upLoadAttachmentFile(String filePath, StringCallback callback) {        File file;        if (filePath == null) {            ToastUtils.showToast("文件不存在");            return;        }        Bitmap smallBitmap = CompressImgUtil.compressImg(filePath);        file = CompressImgUtil.saveBitmapFile(smallBitmap);        OkHttpUtils.post()                .url(NetUtils.URL_UPLOADE_ATTACHMENT_FILE)                .addFile("file1", file.getName(), file)                .build()                .execute(callback);    }    /**     * ZIP上传     *     * @param filePath 手机上传文件的地址     * @param callback     */    public static void upLoadZIPFile(String filePath, StringCallback callback) {        File file;        if (filePath == null) {            ToastUtils.showToast("文件不存在");            return;        }        try {            file = new File(filePath);        } catch (Exception e) {            ToastUtils.showToast("文件不存在");            e.printStackTrace();            return;        }        OkHttpUtils.post()                .url(NetUtils.URL_UPLOADE_ATTACHMENT_FILE)                .addFile("file1", file.getName(), file)                .build()                .execute(callback);    }    /**     * 文件(图片)上传  同步请求     *     * @param filePath     */    public static Response upLoadFileSynchronized(String filePath) {        File file;        Response response = null;        if (filePath == null) {            ToastUtils.showToast("文件不存在");            return null;        }        Bitmap smallBitmap = CompressImgUtil.compressImg(filePath);        file = CompressImgUtil.saveBitmapFile(smallBitmap);        try {            response = OkHttpUtils.post().url(NetUtils.URL_UPLOADE_FILE).addFile("file1", file.getPath(), file).build().execute();        } catch (IOException e) {            e.printStackTrace();            return null;        }        return response;    }    /**     * 多个图片上传  同步     *     * @param imgLocalPathList 多图本地路径集合     */    public static void upLoadFiles(final List<String> imgLocalPathList, final Dialog waitDialog, final Handler handler) {        if (waitDialog != null) {            waitDialog.show();        }        new Thread() {            @Override            public void run() {                ArrayList<String> imgsSignList = new ArrayList<>();                String imgsSignStr = "";                UploadThread uploadThread;                Vector<Thread> vector = new Vector<>();                for (int i = 0; i < imgLocalPathList.size(); i++) {                    uploadThread = new UploadThread(imgLocalPathList.get(i), imgsSignList);                    vector.add(uploadThread);//            uploadThread.start();                }                for (Thread iThread : vector) {                    try {                        // 等待所有线程执行完毕                        iThread.start();                        iThread.join();                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }                for (int i = 0; i < imgsSignList.size(); i++) {                    if (!StringUtils.isEmpty(imgsSignList.get(i))) {                        if (i == 0) {                            imgsSignStr = imgsSignList.get(i);                        } else {                            imgsSignStr = imgsSignStr + "," + imgsSignList.get(i);                        }                    }                }                Message msg = Message.obtain();                msg.obj = imgsSignStr;                handler.sendMessage(msg);            }        }.start();    }    private static class UploadThread extends Thread {        private String path;        private ArrayList imgsSignList;        private UploadResultBean uploadResult;        public UploadThread(String path, ArrayList imgsSignList) {            this.path = path;            this.imgsSignList = imgsSignList;        }        @Override        public void run() {//文件上传  同步请求            Response response = UploadFilesUtil.upLoadFileSynchronized(path);            if (response != null && response.isSuccessful()) {                uploadResult = new Gson().fromJson(response.body().charStream(), UploadResultBean.class);                if (uploadResult.code == 0) {                    imgsSignList.add(uploadResult.message);                }                Log.d("多图上传", "onResponse() returned:上传成功--------- " + uploadResult.msg);            } else {                Log.d("多图上传", "run() returned: " + "上传失败");                Log.d("多图上传", "onResponse() returned:--------- " + uploadResult.msg);            }        }    }}
1.单个文件(图片)的上传。

 /**     * 文件(图片)上传     *     * @param filePath 手机上传文件的地址     * @param callback     */    public static void upLoadFile(String filePath, StringCallback callback) {        File file;        if (filePath == null) {            ToastUtils.showToast("文件不存在");            return;        }        Bitmap smallBitmap = CompressImgUtil.compressImg(filePath);//压缩图片        file = CompressImgUtil.saveBitmapFile(smallBitmap);//Bitmap对象保存为图片文件        OkHttpUtils.post()                .url(NetUtils.URL_UPLOADE_FILE)                .addFile("file1", file.getName(), file)                .build()                .execute(callback);    }
这是基于post 的单个文件上传,我们会发现其中有对图片的压缩操作,不要着急,如果你想了解的话:图片压缩  Bitmap对象保存为图片文件。
2.多个文件(图片)上传。

对于多张图片上传,我们就要考虑文件上传的的速度问题了,如果同时在一个子线程里上传9张图片,那么上传的速度是非常慢的,虽然说也能上传成功,但是用户体验就比较差了,那么我们就要开启多个线程来上传多张图片了。

/**     * 多个图片上传  同步     * @param imgLocalPathList 多图本地路径集合     */    public static void upLoadFiles(final List<String> imgLocalPathList, final Dialog waitDialog, final Handler handler) {        if (waitDialog != null) {            waitDialog.show(); //上传时的dialog加载框        }        new Thread() {            @Override            public void run() {                ArrayList<String> imgsSignList = new ArrayList<>();                String imgsSignStr = "";                UploadThread uploadThread;                Vector<Thread> vector = new Vector<>();//vector 动态数组                for (int i = 0; i < imgLocalPathList.size(); i++) {                    uploadThread = new UploadThread(imgLocalPathList.get(i), imgsSignList);//多少张图片new多少个线程                    vector.add(uploadThread);//            uploadThread.start();                }                for (Thread iThread : vector) {                    try {                        // 等待所有线程执行完毕                        iThread.start();                        iThread.join();                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }                for (int i = 0; i < imgsSignList.size(); i++) {                    if (!StringUtils.isEmpty(imgsSignList.get(i))) {                        if (i == 0) {                            imgsSignStr = imgsSignList.get(i);                        } else {                            imgsSignStr = imgsSignStr + "," + imgsSignList.get(i);                        }                    }                }                Message msg = Message.obtain();                msg.obj = imgsSignStr;                handler.sendMessage(msg);            }        }.start();    }
这里在开线程是有一个vector 需要了解,请参考:http://blog.csdn.net/javaeeteacher/article/details/1533732

http://blog.sina.com.cn/s/blog_8d13a22b01010jcz.html

线程:

 private static class UploadThread extends Thread {        private String path;        private ArrayList imgsSignList;        private UploadResultBean uploadResult;        public UploadThread(String path, ArrayList imgsSignList) {            this.path = path;            this.imgsSignList = imgsSignList;        }        @Override        public void run() {//文件上传  同步请求            Response response = UploadFilesUtil.upLoadFileSynchronized(path);            if (response != null && response.isSuccessful()) {                uploadResult = new Gson().fromJson(response.body().charStream(), UploadResultBean.class);                if (uploadResult.code == 0) {                    imgsSignList.add(uploadResult.message);                }                Log.d("多图上传", "onResponse() returned:上传成功--------- " + uploadResult.msg);            } else {                Log.d("多图上传", "run() returned: " + "上传失败");                Log.d("多图上传", "onResponse() returned:--------- " + uploadResult.msg);            }        }    }
同步请求:
   /**     * 文件(图片)上传  同步请求     *     * @param filePath     */    public static Response upLoadFileSynchronized(String filePath) {        File file;        Response response = null;        if (filePath == null) {            ToastUtils.showToast("文件不存在");            return null;        }/*        try {            file = new File(filePath);        } catch (Exception e) {            ToastUtils.showToast("文件不存在");            e.printStackTrace();            return null;        }*/        Bitmap smallBitmap = CompressImgUtil.compressImg(filePath);        file = CompressImgUtil.saveBitmapFile(smallBitmap);        try {            response = OkHttpUtils.post().url(NetUtils.URL_UPLOADE_FILE).addFile("file1", file.getPath(), file).build().execute();        } catch (IOException e) {            e.printStackTrace();            return null;        }        return response;    }

3.压缩ZIP文件的上传

 /**     * ZIP上传     *     * @param filePath 手机上传文件的地址     * @param callback     */    public static void upLoadZIPFile(String filePath, StringCallback callback) {        File file;        if (filePath == null) {            ToastUtils.showToast("文件不存在");            return;        }        try {            file = new File(filePath);        } catch (Exception e) {            ToastUtils.showToast("文件不存在");            e.printStackTrace();            return;        }        OkHttpUtils.post()                .url(NetUtils.URL_UPLOADE_ATTACHMENT_FILE)                .addFile("file1", file.getName(), file)                .build()                .execute(callback);    }

对于文件的ZIP压缩参考:http://blog.csdn.net/lijinweii/article/details/73498358