安卓之上傳檔案,即HTTP提交表單

來源:互聯網
上載者:User

標籤:

擷取檔案:

    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); 
        /* 通過BundleObject Storage Service需要傳遞的資料 */ 
        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提交表單

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.