Android:上传图片工具类

参考:
Android上传文件的几种方式
android 文件上传(POST方式模拟表单提交)
[android]模拟Http表单,实现本地文件(图片等)上传到服务器端
Android模拟 HTTP multipart/form-data 请求协议信息实现图片上传

上传图片工具类


/**
 * HttpUrlConnection上传图片等文件工具类
 * <p>
 * xq
 */

public class HucUploadFile {

    private static String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
    private static String PREFIX = "--";
    private static String LINE_END = "\r\n";
    private static String CONTENT_TYPE = "multipart/form-data"; // 内容类型
    private static String CHARSET = "utf-8"; // 设置编码

    /**
     * 上传文件
     *
     * @param requestUrl:请求URL
     * @param params:key-value
     * @param files:string:文件名,file:文件路径
     * @return
     */
    public static String post(String requestUrl, Map<String, String> params, Map<String, File> files) {

        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//            conn.setChunkedStreamingMode(0);//不加这句话,Android上传大文件的时候,容易出现内存溢出。
            conn.setReadTimeout(5 * 1000);
            conn.setConnectTimeout(5 * 1000);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", CHARSET); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
//            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

            DataOutputStream dataOutputStream = new DataOutputStream(conn.getOutputStream());
            //  添加表单字段内容
            addFormField(params, dataOutputStream);
            //  添加图片内容
            addImageContent(files, dataOutputStream);
            //  请求结束标志
            dataOutputStream.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);//写入
            dataOutputStream.flush();

            //得到响应码
            int responseCode = conn.getResponseCode();
            InputStream inputStream = conn.getInputStream();
            StringBuilder stringBuilder = new StringBuilder();
            if (responseCode == 200) {
                int ch;
                while ((ch = inputStream.read()) != -1) {
                    stringBuilder.append((char) ch);
                }
            }

            dataOutputStream.close();
            conn.disconnect();
            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 格式如下所示:
     * --****************fD4fH3hK7aI6
     * Content-Disposition: form-data; name="action"
     * // 一空行,必须有
     *
     * @param params
     * @param dataOutputStream
     * @throws IOException
     */
    private static void addFormField(Map<String, String> params, DataOutputStream dataOutputStream) throws IOException {
        //构建表单字段内容:文本类型
        if (params != null) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                sb.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"").append(LINE_END);
//                    sb.append("Content-Type: text/plain; charset=").append(CHARSET).append(LINE_END);
                sb.append(LINE_END);
                sb.append(entry.getValue());
                sb.append(LINE_END);
            }
            dataOutputStream.write(sb.toString().getBytes());//写入
        }
    }

    /**
     * 格式如下所示:
     * --****************fD4fH3hK7aI6
     * Content-Disposition: form-data; name="upload_file"; filename="apple.jpg"
     * Content-Type: image/jpeg
     *
     * @param files
     * @param dataOutputStream
     * @throws IOException
     */
    private static void addImageContent(Map<String, File> files, DataOutputStream dataOutputStream) throws IOException {
        //文件的上传配置:二进制流
        if (files != null) {
            for (Map.Entry<String, File> file : files.entrySet()) {
                StringBuilder sb = new StringBuilder();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                sb.append("Content-Disposition: form-data; name=\"file\";filename=\"" + file.getKey() + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
                sb.append(LINE_END);
                dataOutputStream.write(sb.toString().getBytes());//发送图片数据

                FileInputStream is = new FileInputStream(file.getValue());
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    dataOutputStream.write(buffer, 0, len);
                }
                is.close();
                dataOutputStream.write(LINE_END.getBytes());//写入
            }
        }
    }

}

项目示例:

HttpUtil

public class HttpUtil {
    public static HttpUtil http = new HttpUtil();

    public static HttpUtil getHttp() {
        return http;
    }

    private String user_agent;


    /**
     * POST请求
     *
     * @param
     */
    public String upLoadRequset(final String url, final File file) {

        if (!NetUtil.isNetworkAvailable(DchApplication.getContext())) {
            ToastUtil.showToast(DchApplication.getContext(), "网络异常,请查看网络设置");
            return "";
        }

        user_agent = DchApplication.getInstance().getUserAgent();

        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return UploadUtil.uploadFile(file, url,user_agent);
            }
        });

        new Thread(task).start();

        String s = null;
        try {
            s = task.get();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return s;
    }
}

UploadUtil

/**
 * 上传文件到服务器类
 */
public class UploadUtil {

    private static final int TIME_OUT = 10 * 1000; // 超时时间
    private static String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
    private static String PREFIX = "--";
    private static String LINE_END = "\r\n";
    private static String CONTENT_TYPE = "multipart/form-data"; // 内容类型
    private static String CHARSET = "utf-8"; // 设置编码


    /**
     * Android上传文件到服务端
     */
    public static String uploadFile(File file, String RequestURL, String user_agent) {
        String result = "";

        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", CHARSET); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

            conn.setRequestProperty("AppClient", Constant.AppClient);
            conn.setRequestProperty("AppVersionCode", Constant.AppVersionCode);
            conn.setRequestProperty("UMChannelId", Constant.UMChannelId);
            String token = (String) SharePerfenceUtil.getParam("token", "");
            conn.setRequestProperty("Token", token);
            String DeviceId = Constant.getDeviceId();
            if (!TextUtils.isEmpty(DeviceId)) {
                conn.setRequestProperty("DeviceId", DeviceId);
            }
            if (!TextUtils.isEmpty(user_agent)) {
                conn.setRequestProperty("HTTP_USER_AGENT", user_agent);
            }
//            Log.e("MyCenterActivity", "user_agent==" + user_agent);
//            Log.e("MyCenterActivity", "DeviceId==" + DeviceId);
//            Log.e("MyCenterActivity", "token==" + token);
//            Log.e("MyCenterActivity", "Constant.UMChannelId==" + Constant.UMChannelId);
//            Log.e("MyCenterActivity", "Constant.AppClient==" + Constant.AppClient);
//            Log.e("MyCenterActivity", "Constant.AppVersionCode==" + Constant.AppVersionCode);


            DataOutputStream dataOutputStream = new DataOutputStream(conn.getOutputStream());
            //  添加表单字段内容
//            addFormField(params, dataOutputStream);
            //  添加图片内容
            addImageContent(file, dataOutputStream);
            //  请求结束标志
            dataOutputStream.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);//写入
            dataOutputStream.flush();

            // 读取服务器返回结果
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            result = br.readLine();
            Log.e("MyCenterActivity", "result==" + result);
            dataOutputStream.close();
            is.close();

            dataOutputStream.close();
            conn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 格式如下所示:
     * --****************fD4fH3hK7aI6
     * Content-Disposition: form-data; name="action"
     * // 一空行,必须有
     *
     * @param params
     * @param dataOutputStream
     * @throws IOException
     */
    private static void addFormField(Map<String, String> params, DataOutputStream dataOutputStream) throws IOException {
        //构建表单字段内容:文本类型
        if (params != null) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                sb.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"").append(LINE_END);
//                    sb.append("Content-Type: text/plain; charset=").append(CHARSET).append(LINE_END);
                sb.append(LINE_END);
                sb.append(entry.getValue());
                sb.append(LINE_END);
            }
            dataOutputStream.write(sb.toString().getBytes());//写入
        }
    }

    /**
     * 格式如下所示:
     * --****************fD4fH3hK7aI6
     * Content-Disposition: form-data; name="upload_file"; filename="apple.jpg"
     * Content-Type: image/jpeg
     *
     * @param file
     * @param dataOutputStream
     * @throws IOException
     */
    private static void addImageContent(File file, DataOutputStream dataOutputStream) throws IOException {
        //文件的上传配置:二进制流
        if (file != null) {
            StringBuilder sb = new StringBuilder();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);
            //此处重点:name为后台给的字段,filename为上传的文件名
            sb.append("Content-Disposition: form-data; name=\"upload\";filename=\"head.jpg\"" + LINE_END);
            //此处重点:上传的为JPG图片,那么图片Content-Type为 image/jpeg
            sb.append("Content-Type: image/jpeg; charset=" + CHARSET + LINE_END);
            //sb.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""+ file.getName() + "\"" + LINE_END);
            //sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
            sb.append(LINE_END);
            dataOutputStream.write(sb.toString().getBytes());//发送图片数据

            FileInputStream is = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                dataOutputStream.write(buffer, 0, len);
            }
            is.close();
            dataOutputStream.write(LINE_END.getBytes());//写入图片流
        }
    }

    /*------------------------------------------解析上传图片返回---------------------------------------------------*/


    public static String getModelWithJson(String response) {
        String status = "";

        if (response != null) {
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(response);
                if (jsonObject.has("status")) {
                    status = jsonObject.getString("status");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return status;
    }


}

HttpHelper

public class HttpHelper {

    private static HttpHelper httpHelper = new HttpHelper();
    public static HttpHelper getHeper() {
        return httpHelper;
    }

    private HttpUtil httpConnect = HttpUtil.getHttp();

    //上传头像服务器,
    public String uploadImage(File file){
        String url = Constant.APP_DoUploadAvatar_URL;
        String response = httpConnect.upLoadRequset(url, file);
        return UploadUtil.getModelWithJson(response);
    }
}

activity中调用:

 /**
 * 上传服务器代码
 */
 File headImage = new File(Environment.getExternalStorageDirectory().getPath() + "/myHead/head.jpg");
String uploadResult = HttpHelper.getHeper().uploadImage(headImage);
 Log.e("MyCenterActivity", "uploadResult==" + uploadResult);
      if (uploadResult.equals("000")) {
        try {
           Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(headImage));
           //上传成功,显示出来
           mCenterHead.setImageBitmap(bitmap);
        } catch (FileNotFoundException e) {
           e.printStackTrace();
        }
 }
Android 上传文件至服务器和下载文件至本地,亲测有效,只需传入相关参数即可。/** * android上传文件到服务器 * * @param file * 需要上传的文件 * @param RequestURL * 请求的rul * @return 返回响应的内容 */ public static String uploadFile(Map<String,String>params,File file, String RequestURL) { String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (file != null) { Log.i(TAG, "====file is"+file); /** * 当文件不为空,把文件包装并且上传 */ OutputStream outputSteam = conn.getOutputStream(); DataOutputStream dos = new DataOutputStream(outputSteam); StringBuffer sb = new StringBuffer(); /************************上传表单的一些设置信息***********************************/ if (params != null) for (String key : params.keySet()) { sb.append("--" + BOUNDARY + "\r\n"); sb.append("Content-Disposition: form-data; name=\"" + key + "\"" + "\r\n"); sb.append("\r\n"); sb.append(params.get(key) + "\r\n"); } /************************上传文件的一些设置信息***********************************/ sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.p
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值