码迷,mamicode.com
首页 > 移动开发 > 详细

安卓之上传文件,即HTTP提交表单

时间:2015-06-27 09:41:04      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

获取文件:

    public void Init()
    {
        noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
        noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        adapter = new GridAdapter(this);
        adapter.update1();
        noScrollgridview.setAdapter(adapter);
        noScrollgridview.setOnItemClickListener(new OnItemClickListener()
        {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3)
            {
                InputMethodManager imm = ( InputMethodManager ) arg1.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE );  
                 imm.hideSoftInputFromWindow( arg1.getApplicationWindowToken( ) , 0 );  
                if (arg2 == Bimp.bmp.size())
                {
                    new PopupWindows(PublishedActivity.this, noScrollgridview);
                }
                else
                {
                    Intent intent = new Intent(PublishedActivity.this,
                            PhotoActivity.class);
                    intent.putExtra("ID", arg2);
                    startActivity(intent);
                }
            }
        });
        activity_selectimg_send = (Button) findViewById(R.id.activity_selectimg_send);
        activity_selectimg_send.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

        //showDialog("ddd");
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .permitNetwork().build());

        List<String> list = new ArrayList<String>();
        for (int i = 0; i < Bimp.drr.size(); i++)
        {
            String Str = Bimp.drr.get(i).substring(
                    Bimp.drr.get(i).lastIndexOf("/") + 1,
                    Bimp.drr.get(i).lastIndexOf("."));
            list.add(FileUtils.SDPATH + Str + ".JPEG");
            String path = Bimp.drr.get(i);
//            showDialog(path);
//            showDialog(getDataValue("_member_id"));
//            showDialog(((TextView) findViewById(R.id.activity_selectxxx_send)).getText().toString());
            String fileKey = "imgFile"; 
                   UploadUtil uploadUtil = UploadUtil.getInstance();; 
                  uploadUtil.setOnUploadProcessListener(PublishedActivity.this);  //设置监听器监听上传状态 
                   Map<String, String> params = new HashMap<String, String>(); 
                   params.put("userid", getDataValue("_member_id")); 
                   params.put("content", ((TextView) findViewById(R.id.activity_selectxxx_send)).getText().toString()); 
                   uploadUtil.uploadFile( path,fileKey, "http://shop.tminji.com/sns/SendAMessage",params);

            //String x = ((TextView)v.findViewById(R.id.activity_selectxxx_send)).getText().toString();
            //uploadFile(path);
        }
        // 高清的压缩图片全部就在 list 路径里面了
        // 高清的压缩过的 bmp 对象 都在 Bimp.bmp里面
        // 完成上传服务器后 .........
        showDialog("发布成功^_^");
        FileUtils.deleteDir();
//        Intent intent = new Intent(PublishedActivity.this, MainActivity.class);
//        Bundle bundle = new Bundle(); 
//        /*字符、字符串、布尔、字节数组、浮点数等等,都可以传*/ 
//        bundle.putString("Name", "feng88724"); 
//        /*把bundle对象assign给Intent*/ 
//       
//        intent.setClass(PublishedActivity.this, MainActivity.class);
//        intent.putExtras(bundle); 
//        startActivity(intent);
        Intent intentx = new Intent(PublishedActivity.this, MainActivity.class); 
        /* 通过Bundle对象存储需要传递的数据 */ 
        Bundle bundle = new Bundle(); 
        /*字符、字符串、布尔、字节数组、浮点数等等,都可以传*/ 
        bundle.putString("Name", "feng88724"); 
        /*把bundle对象assign给Intent*/ 
        intentx.putExtras(bundle); 
        startActivity(intentx); 
        }});
    }

 

上传文件

private void toUploadFile(File file, String fileKey, String RequestURL,
        Map<String, String> param) {
    String result = null;
    requestTime= 0;
    long requestTime = System.currentTimeMillis();
    long responseTime = 0;

    try {
        URL url = new URL(RequestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(readTimeOut);
        conn.setConnectTimeout(connectTimeout);
        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);
        //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        /**
         * 当文件不为空,把文件包装并且上传
         */
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        StringBuffer sb = null;
        String params = "";
        /***
         * 以下是用于上传参数
         */
        if (param != null && param.size() > 0) {
            Iterator<String> it = param.keySet().iterator();
            while (it.hasNext()) {
                sb = null;
                sb = new StringBuffer();
                String key = it.next();
                String value = param.get(key);
                sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
                sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_END).append(LINE_END);
                sb.append(value).append(LINE_END);
                params = sb.toString();
                Log.i(TAG, key+"="+params+"##");
                dos.write(params.getBytes());
                //dos.flush();
            }
        }
        sb = null;
        params = null;
        sb = new StringBuffer();
        /**
         * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
         * filename是文件的名字,包含后缀名的 比如:abc.png
         */
        sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
        sb.append("Content-Disposition:form-data; name=\"" + fileKey
                + "\"; filename=\"" + file.getName() + "\"" + LINE_END);
        sb.append("Content-Type:image/pjpeg" + LINE_END); // 这里配置的Content-type很重要的 ,用于服务器端辨别文件的类型的
        sb.append(LINE_END);
        params = sb.toString();
        sb = null;
        Log.i(TAG, file.getName()+"=" + params+"##");
        dos.write(params.getBytes());
        /**上传文件*/
        InputStream is = new FileInputStream(file);
        onUploadProcessListener.initUpload((int)file.length());
        byte[] bytes = new byte[1024];
        int len = 0;
        int curLen = 0;
        while ((len = is.read(bytes)) != -1) {
            curLen += len;
            dos.write(bytes, 0, len);
            onUploadProcessListener.onUploadProcess(curLen);
        }
        is.close();
        dos.write(LINE_END.getBytes());
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
        dos.write(end_data);
        dos.flush();
        //dos.write(tempOutputStream.toByteArray());
        /**
         * 获取响应码 200=成功 当响应成功,获取响应的流
         */
        int res = conn.getResponseCode();
        responseTime = System.currentTimeMillis();
        this.requestTime = (int) ((responseTime-requestTime)/1000);
        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.e(TAG, "result : " + result);
            sendMessage(UPLOAD_SUCCESS_CODE, "上传结果:"
                    + result);
            return;
        } else {
            Log.e(TAG, "request error");
            sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:code=" + res);
            return;
        }
    } catch (MalformedURLException e) {
        sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:error=" + e.getMessage());
        e.printStackTrace();
        return;
    } catch (IOException e) {
        sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:error=" + e.getMessage());
        e.printStackTrace();
        return;
    }
}

安卓之上传文件,即HTTP提交表单

标签:

原文地址:http://www.cnblogs.com/luminji/p/4603630.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!