[Android] 上傳照片至PHP server


Client端

1. 先在Manifest.xml加上
 
1
2
3
<uses-permission android:name="android.permission.INTERNET"/>
 
2. 創建一個Activity:UploadFile.java
 
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package com.example.photothrow1;
 
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
 
import android.app.Activity;
import android.app.ProgressDialog;
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;
import android.widget.TextView;
import android.widget.Toast;
  
public class FileUpload extends Activity implements OnClickListener{
     
    private TextView messageText;
    private Button uploadButton, btnselectpic;
    private ImageView imageview;
    private int serverResponseCode = 0;
    private ProgressDialog dialog = null;
        
    private String upLoadServerUri = null;
    private String imagepath=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
         
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_upload);
          
        uploadButton = (Button)findViewById(R.id.uploadButton);
        messageText  = (TextView)findViewById(R.id.messageText);
        btnselectpic = (Button)findViewById(R.id.button_selectpic);
        imageview = (ImageView)findViewById(R.id.imageView_pic);
         
        btnselectpic.setOnClickListener(this);
        uploadButton.setOnClickListener(this);
        upLoadServerUri = "http://你的IP地址/UploadToServer.php";
    }
      
     
    @Override
    public void onClick(View arg0) {
        if(arg0==btnselectpic)
        {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
        }
        else if (arg0==uploadButton) {
             
             dialog = ProgressDialog.show(FileUpload.this, "", "Uploading file...", true);
             messageText.setText("uploading started.....");
             new Thread(new Runnable() {
                 public void run() {
                                      
                      uploadFile(imagepath);
                                               
                 }
               }).start();    
        }
         
    }
     
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         
        if (requestCode == 1 && resultCode == RESULT_OK) {
            //Bitmap photo = (Bitmap) data.getData().getPath();
           
            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
            Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
            imageview.setImageBitmap(bitmap);
            messageText.setText("Uploading file path:" +imagepath);
             
        }
    }
         public String getPath(Uri uri) {
                String[] projection = { MediaStore.Images.Media.DATA };
                Cursor cursor = managedQuery(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            }
         
    public int uploadFile(String sourceFileUri) {
           
           
          String fileName = sourceFileUri;
  
          HttpURLConnection conn = null;
          DataOutputStream dos = null
          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary = "*****";
          int bytesRead, bytesAvailable, bufferSize;
          byte[] buffer;
          int maxBufferSize = 1 * 1024 * 1024;
          File sourceFile = new File(sourceFileUri);
           
          if (!sourceFile.isFile()) {
               
               dialog.dismiss();
                
               Log.e("uploadFile", "Source File not exist :"+imagepath);
                
               runOnUiThread(new Runnable() {
                   public void run() {
                       messageText.setText("Source File not exist :"+ imagepath);
                   }
               });
                
               return 0;
            
          }
          else
          {
               try {
                    
                     // open a URL connection to the Servlet
                   FileInputStream fileInputStream = new FileInputStream(sourceFile);
                   URL url = new URL(upLoadServerUri);
                    
                   // Open a HTTP  connection to  the URL
                   conn = (HttpURLConnection) url.openConnection();
                   conn.setDoInput(true); // Allow Inputs
                   conn.setDoOutput(true); // Allow Outputs
                   conn.setUseCaches(false); // Don't use a Cached Copy
                   conn.setRequestMethod("POST");
                   conn.setRequestProperty("Connection", "Keep-Alive");
                   conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                   conn.setRequestProperty("uploaded_file", fileName);
                    
                   dos = new DataOutputStream(conn.getOutputStream());
          
                   dos.writeBytes(twoHyphens + boundary + lineEnd);
                   dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                             + fileName + "\"" + lineEnd);
                    
                   dos.writeBytes(lineEnd);
          
                   // create a buffer of  maximum size
                   bytesAvailable = fileInputStream.available();
          
                   bufferSize = Math.min(bytesAvailable, maxBufferSize);
                   buffer = new byte[bufferSize];
          
                   // read file and write it into form...
                   bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
                      
                   while (bytesRead > 0) {
                        
                     dos.write(buffer, 0, bufferSize);
                     bytesAvailable = fileInputStream.available();
                     bufferSize = Math.min(bytesAvailable, maxBufferSize);
                     bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
                      
                    }
          
                   // send multipart form data necesssary after file data...
                   dos.writeBytes(lineEnd);
                   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
          
                   // Responses from the server (code and message)
                   serverResponseCode = conn.getResponseCode();
                   String serverResponseMessage = conn.getResponseMessage();
                     
                   Log.i("uploadFile", "HTTP Response is : "
                           + serverResponseMessage + ": " + serverResponseCode);
                    
                   if(serverResponseCode == 200){
                        
                       runOnUiThread(new Runnable() {
                            public void run() {
                                String msg = "File Upload Completed.\n\n See uploaded file your server. \n\n";
                                messageText.setText(msg);
                                Toast.makeText(FileUpload.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                            }
                        });               
                   }   
                    
                   //close the streams //
                   fileInputStream.close();
                   dos.flush();
                   dos.close();
                     
              } catch (MalformedURLException ex) {
                   
                  dialog.dismiss(); 
                  ex.printStackTrace();
                   
                  runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("MalformedURLException Exception : check script url.");
                          Toast.makeText(FileUpload.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                      }
                  });
                   
                  Log.e("Upload file to server", "error: " + ex.getMessage(), ex); 
              } catch (Exception e) {
                   
                  dialog.dismiss(); 
                  e.printStackTrace();
                   
                  runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("Got Exception : see logcat ");
                          Toast.makeText(FileUpload.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                      }
                  });
                  Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e); 
              }
              dialog.dismiss();      
              return serverResponseCode;
               
           } // End else block
         }
 
     
}
 
3. layout.xml
 
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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
 
    <ImageView
        android:id="@+id/imageView_pic"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:src="@drawable/ic_launcher" />
 
    <Button
        android:id="@+id/button_selectpic"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Select Picture" />
 
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click To Upload File"
        android:id="@+id/uploadButton"
    />
       
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:id="@+id/messageText"
        android:textColor="#000000"
        android:textStyle="bold"
    />
 
 </LinearLayout>
 

Server端:

 
1. 新增一個PHP檔到你的Server:UploadToServer.php
 
1
2
3
4
5
6
7
8
9
10
11
<?php
  
   $file_path = "uploads/";
     
   $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
   if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
       echo "success";
   } else{
       echo "fail";
   }
?>
 
2. 新增一個uploads資料夾在相同目錄下
 
廣告

14 thoughts on “[Android] 上傳照片至PHP server

      • 不太懂你的參數指的是圖片參數還是一般的value?
        這個範例是傳整張圖片到你的server目錄底下的
        如果你要傳一般的值,有更簡單的寫法(用 POST)
        google一下資料都很多的!

      • 一般的參數+整張圖片
        我已經解決這問題
        只是想知道這方式是否可以順便傳遞一般的參數而以

      • 喔~可以啊,要再加一些code,不過我沒試過這個方法
        你看我要傳的資料區段是在UploadFile.java的151~176行之間,如果你要傳其他參數,那就再寫一次區段就好了
        每個區段會用boundary來區隔,就是
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        結束的話,要在最後再加上一次twoHyphens,就是177行
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        所以你如果要修改這份code
        可以把下面的code加在177行之前
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes(“Content-Disposition: form-data; name=\"參數名\"" + lineEnd);
        dos.writeBytes(lineEnd);
        dos.writeBytes(參數內容);
        dos.writeBytes(lineEnd);
        這樣就算是一個區段,可以重複多次傳遞不一樣的參數。

        php的地方
        用$_POST[‘參數名’]接就好

    • 什麼意思呢@@,如果是傳模擬器裡的圖片的話,應該都是可以開的
      會不會是你本來就沒有圖片的權限?還是你的server設定問題?

      • 你好 可以了 應該是我sever放在C槽的關係 謝謝 現在有另一個問題想請教一下

        目前已經做到可以上傳資料到mysql了,但圖檔我傳到另外一個硬碟去了,因為C槽權限問題開不了

        現在想要做的是抓取單筆資料核對圖片 一起印出來,像是一個image 下面 textbox這樣
        目前有想到是利用mysql自動編號 1開始+1的那種
        例如資料表新增了一筆資料 Member_No = 20 圖檔名也是20 要如何去做比對後 印出正確的圖加文到android上面

        不好意思 問了這麼長的問題

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s