电竞比分网-中国电竞赛事及体育赛事平台

分享

Android上傳文件到服務(wù)器

 My Laby 2012-03-14

Android上傳文件到服務(wù)器


Android中實(shí)現(xiàn)上傳文件,其實(shí)是很簡單的,和在java里面是一樣的,基本上都是熟悉操作輸出流和輸入流!還有一個(gè)特別重要的就是需要配置content-type的一些參數(shù)!如果這些都弄好了,上傳就很簡單了,下面是我寫的一個(gè)上傳的工具類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package com.spring.sky.image.upload.network;
 
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.util.UUID;
import android.util.Log;
 
/**
 *
 * 上傳工具類
 *
 * @author spring sky Email:vipa1888@163.com QQ:840950105 MyName:石明政
 */
public class UploadUtil {
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 1000; // 超時(shí)時(shí)間
    private static final String CHARSET = "utf-8"; // 設(shè)置編碼
 
    /**
     * Android上傳文具到服務(wù)端
     *
     * @param file
     *            需要上傳的文件
     * @param RequestURL
     *            請求的rul
     * @return 返回響應(yīng)的內(nèi)容
     */
    public static String uploadFile(File file, String RequestURL) {
        String result = null;
        String BOUNDARY = UUID.randomUUID().toString(); // 邊界標(biāo)識 隨機(jī)生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; // 內(nèi)容類型
 
        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); // 設(shè)置編碼
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
                    + BOUNDARY);
 
            if (file != null) {
                /**
                 * 當(dāng)文件不為空,把文件包裝并且上傳
                 */
                DataOutputStream dos = new DataOutputStream(
                        conn.getOutputStream());
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 這里重點(diǎn)注意: name里面的值為服務(wù)端需要key 只有這個(gè)key 才可以得到對應(yīng)的文件
                 * filename是文件的名字,包含后綴名的 比如:abc.png
                 */
 
                sb.append("Content-Disposition: form-data; name=\"img\"; 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());
                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();
                /**
                 * 獲取響應(yīng)碼 200=成功 當(dāng)響應(yīng)成功,獲取響應(yīng)的流
                 */
                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.e(TAG, "result : " + result);
                // }
                // else{
                // Log.e(TAG, "request error");
                // }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

參數(shù)就一個(gè)File文件和一個(gè)請求上傳的URL,不過需要注意的是,因?yàn)橛玫搅司W(wǎng)絡(luò)請求,所以大家不要忘記在上傳的時(shí)候,給android客戶端加一個(gè)訪問網(wǎng)絡(luò)的權(quán)限哦!

還有一點(diǎn)就是需要大家注意一下:本人是做服務(wù)器端javaEE的,我發(fā)現(xiàn)在上傳的過程中,如果文件的標(biāo)識name是java關(guān)鍵字之類的,上傳過程中,會(huì)存在很多位置的問題的!所以大家經(jīng)可能的不要使用關(guān)鍵字哦!

下面是Activity的代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package com.spring.sky.image.upload;
 
import java.io.File;
import com.spring.sky.image.upload.network.UploadUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
 
/**
 * Activity 上傳的界面
 *
 * @author spring sky Email:vipa1888@163.com QQ:840950105 MyName:石明政
 *
 */
public class MainActivity extends Activity implements OnClickListener {
    private static final String TAG = "uploadImage";
    private static String requestURL = ";

layout代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas./apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/selectImage"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="選擇圖片"
        />
    <Button
        android:id="@+id/uploadImage"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="上傳圖片"
        />
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>

以上就是android上傳圖片的全部代碼,如果想上傳其他文件的話,可以修改過濾條件就可以了,同時(shí)文件的類型一定要和服務(wù)器端的文件類型保持一致,否則上傳就失敗了!

如果大家還有在使用過程中,發(fā)現(xiàn)有什么問題可以聯(lián)系我!

    本站是提供個(gè)人知識管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多