android 图片及文本上传至服务器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/generallizhong/article/details/79932204

很久没有写过图片上传,今天写的时候还有点生疏了,这里记录一下:

很简单的一个功能确用了大半天,主要为两部分一是:请求类,二是:界面的调用

1、这里主要是用原生方式进行写图片上传,外加文本一起进进行上传,第一部直接上代码吧!很简单应该不会存在看不懂的

private void UpFile(final TextView view) {
        final String url = "http://" + HttpUtil.baseIp_ + HttpUtil.dk + "/KeyFileUpload.action";//服务器地址
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final Map<String, Object> paramMap = new HashMap<String, Object>(); //文本数据全部添加到Map里
                    paramMap.put("id", "e69c119f642b4b67a8004b2760938c0b");//参数
                    paramMap.put("fileType", "1");//参数
                    final File pictureFile = new File(_path); //通过路径获取文件_path是图片地址
                    Log.e("LZ取出file//", pictureFile.getPath());
                    try {
                        getimgcode = UpImgFile.doPostPicture(getActivity(), pictureFile.getPath(), paramMap, pictureFile);//调用方法
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (getimgcode == 200) {//这里是返回值
                                Toast.makeText(getActivity(), "上传成功!", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getActivity(), "上传失败!", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

                } catch (Exception e) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "请检查是否已签字", Toast.LENGTH_SHORT).show();
                        }
                    });

                }
            }
        }).start();
    }

这里就是调用部分,是在fragment上调用,

第二部分为请求类

public class UpImgFile {

    static String BOUNDARY = java.util.UUID.randomUUID().toString();
    static String PREFIX = "--", LINEND = "\r\n";
    static String MULTIPART_FROM_DATA = "multipart/form-data";
    static String CHARSET = "UTF-8";
    /* 上传文件至Server的方法 */
    /**
     * android上传文件到服务器
     *
     * @param file       需要上传的文件
     * @param RequestURL 请求的rul
     * @return 返回响应的内容
     */
    static final String _http = "http://" + HttpUtil.baseIp_ + HttpUtil.dk + "/KeyFileUpload.action";//这里是服务器的地址

    public static int doPostPicture(Context context, String Strpath, Map<String, Object> paramMap, File pictureFile)
            throws Exception {
        URL url = new URL(_http);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false);
        conn.setReadTimeout(10 * 10000); // 缓存的最长时间
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
        DataOutputStream os = new DataOutputStream(conn.getOutputStream());
        StringBuilder sb = new StringBuilder(); //用StringBuilder拼接报文,用于上传图片数据
        sb.append(PREFIX);
        sb.append(BOUNDARY);
        sb.append(LINEND);
        Log.e("LZ图片路径", pictureFile.getName() + "");
        sb.append("Content-Disposition: form-data; name=\"picture\"; filename=\"" + pictureFile.getName() + "\"" + LINEND);

        sb.append("Content-Type: image/jpg; charset=" + CHARSET + LINEND);
        sb.append(LINEND);
        os.write(sb.toString().getBytes());
        Log.e("Lz截取路径--2", pictureFile.getPath().substring(5));
        InputStream is = new FileInputStream(pictureFile.getPath().substring(5));

        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len); //写入图片数据
        }
        is.close();
        os.write(LINEND.getBytes());

        StringBuilder text = new StringBuilder();
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) { //在for循环中拼接报文,上传文本数据
            text.append("--");
            text.append(BOUNDARY);
            text.append("\r\n");
            text.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
            text.append(entry.getValue());
            text.append("\r\n");
        }
        os.write(text.toString().getBytes("utf-8")); //写入文本数据
        // 请求结束标志
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        os.write(end_data);
        os.flush();
        os.close();
        // 得到响应码
        int res = conn.getResponseCode();
        Log.e("LZ--返回的code:", res + "");
        Log.e("Lz", "msg" + conn.getResponseMessage());
        conn.disconnect();
        return res;
    }
}
这样就可以成功上传了,这里只是一张图片的上传。

下载demo

猜你喜欢

转载自blog.csdn.net/generallizhong/article/details/79932204
今日推荐