• 图片上传


    UploadUtil

    package com.atwal.util;
    
    import android.util.Log;
    
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.Map;
    import java.util.UUID;
    
    /**
     * Created by atwal on 2016/3/11.
     */
    public class UploadUtil {
        private static final String TAG = "uploadFile";
        private static final int TIME_OUT = 10 * 1000;   //超时时间
        private static final String CHARSET = "utf-8";
        private static final String BOUNDARY = UUID.randomUUID().toString();  //边界标识随机生成
        private static final String PREFIX = "--";
        private static final String LINE_END = "
    ";
        private static final String CONTENT_TYPE = "multipart/form-data";   //内容类型
    
        /**
         * 上传文件
         * @param file 文件
         * @param RequestURL post地址
         * @param params 除文件外其他参数
         * @param uploadFieldName 上传文件key
         * @return
         */
        public static String uploadFile(File file, String RequestURL, Map<String, String> params, String uploadFieldName) {
            String result = null;
    
            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);
    
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                StringBuffer sb = new StringBuffer();
                sb.append(getRequestData(params));
    
                if (file != null) {
                    sb.append(PREFIX);
                    sb.append(BOUNDARY);
                    sb.append(LINE_END);
                    sb.append("Content-Disposition: form-data; name="" + uploadFieldName + ""; filename="" + file.getName() + """ + LINE_END);
                    sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
                    sb.append(LINE_END);
                }
                dos.write(sb.toString().getBytes());
                if (file != null) {
                    InputStream is = new FileInputStream(file);
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = is.read(bytes)) != -1) {
                        dos.write(bytes, 0, len);
                    }
                    is.close();
                    dos.write(LINE_END.getBytes());
                    byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                    dos.write(end_data);
                }
                dos.flush();
    
                int res = conn.getResponseCode();
                Log.e(TAG, "response code:" + res);
                if (res == 200) {
                    Log.e(TAG, "request success");
                    InputStream input = conn.getInputStream();
                    StringBuffer sb1 = new StringBuffer();
                    int ss;
                    while ((ss = input.read()) != -1) {
                        sb1.append((char) ss);
                    }
                    result = sb1.toString();
                    Log.i(TAG, "result : " + result);
                } else {
                    Log.e(TAG, "request error");
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
    
        /**
         * 对post参数进行编码处理
         * @param params post参数
         * @return
         */
        private static StringBuffer getRequestData(Map<String, String> params) {
            StringBuffer stringBuffer = new StringBuffer();
            try {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    stringBuffer.append(PREFIX);
                    stringBuffer.append(BOUNDARY);
                    stringBuffer.append(LINE_END);
                    stringBuffer.append("Content-Disposition: form-data; name="" + entry.getKey() + """ + LINE_END);
                    stringBuffer.append(LINE_END);
                    stringBuffer.append(URLEncoder.encode(entry.getValue(), CHARSET));
                    stringBuffer.append(LINE_END);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return stringBuffer;
        }
    }
    

    调用

     String requestURL = "服务器地址";

    String picPath = "图片地址";

    File file = new File(picPath);

    Log.i("upload", "file exists:" + file.exists());

    if (file.exists()) {

    Map<String, String> params = new HashMap<>();

    params.put("id", "1");

    //...如果有其他参数添加到这里

    String request = UploadUtil.uploadFile(file, requestURL, params, "image");

    Log.i("upload", request);

    }

  • 相关阅读:
    概率论
    计算机网络基础
    数据库 数据库管理系统 数据库系统
    第二次冲刺总结
    Beta版总结会议
    Beta阶段项目总结
    beta版本“足够好”/测试矩阵
    zencart批量更新后台邮箱地址sql
    php首页定向到内页代码
    用.htaccess 禁止IP访问
  • 原文地址:https://www.cnblogs.com/yiweiaimeng/p/5354276.html
Copyright © 2020-2023  润新知