Android图片上传工具类
16lz
2021-12-04
package com.wbai.qqsd.util.img;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import org.json.JSONObject;import android.annotation.SuppressLint;import android.content.Context;import android.os.Handler;import android.os.Message;import com.wbai.qqsd.common.Constants;import com.wbai.qqsd.common.SiAppLication;import com.wbai.qqsd.util.db.SaveUserInfoData;import com.wbai.qqsd.util.log.LogUitls;import com.wbai.qqsd.util.ohter.MD5;/** * @类名:UpImageUitls * @功能描述: 上传图片管理工具类<br> * 使用方法:<br> * UpImageUitls imageUitls = new UpImageUitls(监听);<br> * imageUitls.uploadImg(filePath, fileNameKey);//上传单个文件<br> * imageUitls.uploadImg(filePath[], fileNameKey);//批量上传文件<br> * imageUitls.uploadImg(filePath[], * fileNameKey,count);//批量上传文件,控制同时上传文件的数目(推荐使用这个)<br> * @作者:XuanKe'Huang * @时间:2015-5-26 上午11:28:58 * @Copyright @2014 */@SuppressLint("HandlerLeak")public class UpImageUitls { private String urlStr;// 上传地址 private Context context;// 上下文对象 private OnUpResultListener onUpResultListener;// 图片上传监听 private boolean ifLimtedFlag = false;// 上传图片时是否有数量的限制.默认为没有 private String[] uriArr = null;// 当有同时上传图片的数量限制时的图片数组 private String key = null;// 图片key private int currtentPositon = -1;// 当有同时上传图片的数量限制时,当前等待上传的图片位置. public UpImageUitls(Context context, OnUpResultListener onUpResultListener) { this.context = context; this.onUpResultListener = onUpResultListener; urlStr = "地址"; } /** * @类名:OnUpResultListener * @功能描述:上传图片结果监听 * @作者:XuanKe'Huang * @时间:2014-12-19 上午9:56:38 * @Copyright 2014 */ public interface OnUpResultListener { /** * 方法名: success * * 功能描述:图片上传成功回调方法 * * @param successArr * 图片上传成功返回信息.[0]:图片路径(是路径不是Uri).[1]:图片上传成功后的地址(相对地址,以:img/.. * 开头 ) * @return void * * </br>throws */ void success(String[] successArr); /** * 方法名: failure * * 功能描述:图片上传失败回调方法 * * @param errorArr * 图片上传失败返回信息.[0]:图片路径(是路径不是Uri)/"error".[1]:图片上传失败信息 * @return void * * </br>throws */ void failure(String[] errorArr); } /** * @方法名: uploadImg * @功能描述: 单个上传图片 * @param filePath * 图片路径 * @param fileNameKey * 图片key * @return void */ public void uploadImg(final String filePath, final String fileNameKey) { if (filePath == null) {// 检测Uri是否为null onUpResultListener.failure(new String[] { "error", "图片路径不能为null" }); return; } final File file = new File(filePath); if (!file.exists()) {// 检查图片是否存在 onUpResultListener .failure(new String[] { filePath, "图片不存在,可能已被删除" }); return; } if (SiAppLication.getApplicationInstance().isNetWork()) {// 有网络 new Thread(new Runnable() { @Override public void run() { uploadFileFinal(urlStr, fileNameKey, file, handler); } }).start(); } else {// 没网络 onUpResultListener.failure(new String[] { filePath, "网络不可用" }); } } /** * @方法名: uploadImg * @功能描述: 图片批量上传 * @param filePath * 需要上传的图片的地址数组 * @param fileNameKey * 图片key * @return void */ public void uploadImg(final String[] filePath, final String fileNameKey) { if (filePath == null) {// 判断图片是否为null onUpResultListener.failure(new String[] { "error", "图片数组不能为null" }); return; } for (int i = 0; i < filePath.length; i++) { final String path = filePath[i]; uploadImg(path, fileNameKey); } } /** * @方法名: uploadImg * @功能描述: 图片批量上传(可选择同时上传的图片个数) * @param filePath * 需要上传的图片的地址数组 * @param fileNameKey * 图片key * @param count * 同时上传图片的最大个数(防止OOM) * @return void */ public void uploadImg(final String[] filePath, final String fileNameKey, int count) { if (filePath == null) {// 判断图片是否为null onUpResultListener.failure(new String[] { "error", "图片数组不能为null" }); return; } if (count < 1) {// 批量执行的数目不能小于1 onUpResultListener.failure(new String[] { "error", "同时上传图片最大个数不能小于1" }); return; } this.key = fileNameKey;// 得到图片的key this.uriArr = filePath;// 得到有图片上传限制时的图片Uri数组 ifLimtedFlag = true;// 把标志位设置为有限制 int tmpCount = count > uriArr.length ? uriArr.length : count;// 得到批量执行的个数 currtentPositon = tmpCount;// 初始化当前等待执行的个数 for (int i = 0; i < tmpCount; i++) {// 第一次开启最大数量的线程 final String path = filePath[i]; uploadImg(path, fileNameKey); } } private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case 10086:// 成功 onUpResultListener.success((String[]) msg.obj); break; case 10087:// 失败 onUpResultListener.failure((String[]) msg.obj); break; } if (ifLimtedFlag) {// 如果有后续任务 limitedUpListener.upNextImg(); } }; }; /** * @变量名 limitedUpListener: 有上传个数限制时的监听回调 */ private LimitedUpListener limitedUpListener = new LimitedUpListener() { @Override public void upNextImg() { if (currtentPositon < uriArr.length) {// 上传下一个图片 uploadImg(uriArr[currtentPositon++], key); } } }; private interface LimitedUpListener { /** * 方法名: upNextImg * * 功能描述:上传下一个图片 * * @return void * * </br>throws */ void upNextImg(); } /** * @方法名: uploadFileFinal * @功能描述: 上传图片 * @param serviceUrl * 上传地址 * @param key * 图片key * @param file * 需要上传的图片 * @param handler * handler回调 * @return void */ public synchronized void uploadFileFinal(String serviceUrl, String key, File file, Handler handler) { Message message = new Message(); String end = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; try { URL url = new URL(serviceUrl + key); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); /* 允许Input、Output,不使用Cache */ conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); /* 设置传送的method=POST */ conn.setRequestMethod("POST"); /* setRequestProperty */ conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); /* 设置DataOutputStream */ DataOutputStream ds = new DataOutputStream(conn.getOutputStream()); ds.writeBytes(twoHyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; " + "name=\"" + key + "\";filename=\"" + file.getName() + "\"" + end); ds.writeBytes(end); /* 取得文件的FileInputStream */ FileInputStream fStream = new FileInputStream(file.getPath()); /* 设置每次写入1024bytes */ int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int length = -1; /* 从文件读取数据至缓冲区 */ while ((length = fStream.read(buffer)) != -1) { /* 将资料写入DataOutputStream中 */ ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(twoHyphens + boundary + twoHyphens + end); /* close streams */ fStream.close(); ds.flush(); /* 关闭DataOutputStream */ ds.close(); /* 取得Response内容 */ int res = conn.getResponseCode(); LogUitls.print("siyehua", res); if (res == 200) {// 成功 System.setProperty("http.keepAlive", "false"); InputStream is = conn.getInputStream(); int ch; StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } is.close(); JSONObject jsonObject = new JSONObject(new String(b.toString() .getBytes("ISO-8859-1"), "UTF-8")); if (jsonObject.getInt("code") > 0) { message.what = 10086; message.obj = new String[] { file.getPath(), jsonObject.getJSONObject("data").getString("url") }; handler.sendMessage(message); } else { message.what = 10087; message.obj = new String[] { file.getPath(), jsonObject.getString("msg") }; handler.sendMessage(message); } } else if (res == 500) {// 请求超时,中断 message.what = 10087; message.obj = new String[] { file.getPath(), "请求超时" }; handler.sendMessage(message); } else {// 其他 message.what = 10087; message.obj = new String[] { file.getPath(), "错误" }; handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); message.what = 10087; message.obj = new String[] { file.getPath(), "设置错误" }; handler.sendMessage(message); } }}
更多相关文章
- android 获取网络图片
- Android使用HttpURLConnection上传文件
- Android(安卓)自定义控件之图片裁剪
- android访问网络图片
- 【Android】简单图片浏览器
- android图像处理系列之三--图片色调饱和度、色相、亮度处理
- android checkbox 定制(修改checkbox 的图片)
- Android使用xml自定义图片
- Android(安卓)图片缩放与旋转