Android - Uploader Une Image Sur Un Serveur Web - Dans Un An...
Android - Uploader Une Image Sur Un Serveur Web - Dans Un An...
Android - Uploader Une Image Sur Un Serveur Web - Dans Un An...
Un petit tuto pour apprendre à uploader une image (jpg ou autre) depuis votre application android vers un
serveur web.
Pour ce genre de tâche qui peut être longue, Android conseille d’implémenter un Service plutôt qu’une activité : un
service tourne en tâche de fond et ne bloque pas l’application.
Pour ce tuto :
view sourceprint?
01.package com.test.upload;
02.
03.import java.io.File;
04.
05.import android.app.Activity;
06.import android.content.Intent;
07.import android.net.Uri;
08.import android.os.Bundle;
09.import android.util.Log;
10.import android.view.View;
11.import android.view.View.OnClickListener;
12.import android.widget.Button;
13.public class TutoUpload extends Activity {
14.
15. protected Uri image=null; //acces au fichier via contentResolver
16. File fichier; //le fichier à uploader
17.
18. /** Called when the activity is first created. */
19. @Override
20. public void onCreate(Bundle savedInstanceState) {
21. super.onCreate(savedInstanceState);
22. setContentView(R.layout.main);
23.
24. //un bouton pour envoi du fichier vers le serveur
25. final Button validbutton = (Button) findViewById(R.id.send);
26. validbutton.setOnClickListener(send_listener);
27. }
28.
29. //pour valider tout pour envoi vers site web
30. OnClickListener send_listener = new OnClickListener() {
31. public void onClick(View v) {
32.
33. image = Uri.fromFile(fichier);
34. Intent uploadIntent = new Intent( );
35. uploadIntent.setClassName("com.test.upload", "com.test.upload.HttpUploader");
36. uploadIntent.setData(image);
37. startService(uploadIntent);
38. }
39. };
40.
41. @Override
42. protected void onPause() {
43. super.onPause();
44. }
45.
46. @Override
47. protected void onStop() {
48. Log.i(getClass().getSimpleName(),"on stop");
…dauran.com/194-android-uploader-u… 1/6
31/01/2011 Android : uploader une image sur un s…
49. super.onStop();
50. }
51.
52. @Override
53. protected void onDestroy() {
54. super.onDestroy();
55. }
56.}
view sourceprint?
001.package com.test.upload;
002.
003.import java.io.BufferedReader;
004.import java.io.DataOutputStream;
005.import java.io.FileNotFoundException;
006.import java.io.IOException;
007.import java.io.InputStream;
008.import java.io.InputStreamReader;
009.import java.net.HttpURLConnection;
010.import java.net.MalformedURLException;
011.import java.net.URL;
012.
013.import android.app.Service;
014.import android.content.ContentResolver;
015.import android.content.Intent;
016.import android.provider.MediaStore;
017.import android.database.Cursor;
018.import android.net.Uri;
019.import android.os.Handler;
020.import android.os.HandlerThread;
021.import android.os.IBinder;
022.import android.os.Looper;
023.import android.os.Message;
024.import android.util.Log;
025.import android.widget.Toast;
026.
027.public class HttpUploader extends Service {
028.
029. private Intent mInvokeIntent;
030. private volatile Looper mUploadLooper;
031. private volatile ServiceHandler mUploadHandler;
032.
033. private int check = 0;
034.
035. private final class ServiceHandler extends Handler {
036. public ServiceHandler(Looper looper) {
037. super(looper);
038. }
039.
040. @Override
041. public void handleMessage(Message msg) {
042. //get extra datas
043. Uri selectedImg = (Uri)msg.obj;
044. Log.i(getClass().getSimpleName(),"selectedImg =" + selectedImg);
045.
046. //upload the file to the web server
047. doHttpUpload(selectedImg);
048.
049. Log.i(getClass().getSimpleName(), "Message: " + msg);
050. Log.i(getClass().getSimpleName(), "Done with #" + msg.arg1);
051. stopSelf(msg.arg1);
052. }
053. };
054.
…dauran.com/194-android-uploader-u… 2/6
31/01/2011 Android : uploader une image sur un s…
055. // Method called when (an instance of) the Service is created
056. public void onCreate() {
057. Log.i(getClass().getSimpleName(),"HttpUploader on create");
058.
059. // This is who should be launched if the user selects our persistent
060. // notification.
061. mInvokeIntent = new Intent();
062. mInvokeIntent.setClassName("com.test.upload", "com.test.upload.HttpUploader");
063.
064. // Start up the thread running the service. Note that we create a
065. // separate thread because the service normally runs in the process's
066. // main thread, which we don't want to block.
067. HandlerThread thread = new HandlerThread("HttpUploader");
068. thread.start();
069.
070. mUploadLooper = thread.getLooper();
071. mUploadHandler = new ServiceHandler(mUploadLooper);
072. }
073.
074. public void onStart(Intent uploadintent, int startId) {
075. // recup des data pour envoi via msg dans la msgqueue pour traitement
076. Message msg = mUploadHandler.obtainMessage();
077. msg.arg1 = startId;
078. //on place l'uri reçu dans l'intent dans le msg pour le handler
079. msg.obj = uploadintent.getData();
080. mUploadHandler.sendMessage(msg);
081. Log.d(getClass().getSimpleName(), "Sending: " + msg);
082.
083. }
084.
085. public void doHttpUpload(Uri myImage) {
086. String lineEnd = "\r\n";
087. String twoHyphens = "--";
088. String boundary = "*****";
089. String photofile = null;
090. String httpResponse; //to read http response
091. String filename=null;
092.
093. String urlString = "http://www.site.com/fileUpload.php";
094. HttpURLConnection conn = null;
095.
096. InputStream fis = null;
097. Bitmap mBitmap=null;
098. String pathfile;
099.
100. if (myImage != null) {
101. //on récupère le nom du fichier photo construit avec date et heure
102. filename = "photo.jpg";
103.
104. String[] projection = { MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.DISPLAY_NAME};
105. ContentResolver cr = getContentResolver();
106. Cursor c = cr.query(myImage, projection, null, null, null);
107. if (c!=null && c.moveToFirst()) {
108. pathfile = c.getString(0); //column0Value
109. photofile = c.getString(1); //column1Value
110. Log.i(getClass().getSimpleName(),"Data : " +pathfile);
111. Log.i(getClass().getSimpleName(),"Display name : " + photofile);
112. }
113.
114. try {
115. fis = getContentResolver().openInputStream(myImage);
116. mBitmap = BitmapFactory.decodeStream(fis);
117.
118. try {
…dauran.com/194-android-uploader-u… 3/6
31/01/2011 Android : uploader une image sur un s…
119. int bytesAvailable = fis.available();
120. } catch (IOException e) {
121. // TODO Auto-generated catch block
122. e.printStackTrace();
123. Log.i(getClass().getSimpleName(),"échec de lecture de la photo");
124. stopSelf();
125. }
126. } catch (FileNotFoundException e) {
127. e.printStackTrace();
128. Toast.makeText(HttpUploader.this, "échec de lecture de la photo ",
Toast.LENGTH_SHORT).show();
129. Log.i(getClass().getSimpleName(),"échec de lecture de la photo");
130. stopSelf();
131. }
132.
133. } else Log.i(getClass().getSimpleName(),"myImage is null");
134.
135. try {
136. URL site = new URL(urlString);
137. conn = (HttpURLConnection) site.openConnection();
138.
139. //on peut écrire et lire
140. conn.setDoOutput(true);
141. conn.setDoInput(true);
142.
143. // Use a post method.
144. conn.setRequestMethod("POST");
145. conn.setRequestProperty("Connection", "Keep-Alive");
146. conn.setRequestProperty("Content-Type", "multipart/form-
data;boundary="+boundary);
147.
148. DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
149.
150. dos.writeBytes(twoHyphens + boundary + lineEnd);
151. Log.i(getClass().getSimpleName(),"Display name : " + photofile);
152. Log.i(getClass().getSimpleName(),"Filename : " + filename);
153. dos.writeBytes("Content-Disposition: form-data;
name=\"uploadedfile\";filename=\"" + filename + "\"" + lineEnd);
154. dos.writeBytes(lineEnd);
155.
156. Log.i(getClass().getSimpleName(),"Headers are written");
157.
158. //compression de image pour envoi
159. mBitmap.compress(CompressFormat.JPEG, 75, dos);
160.
161. // send multipart form data necesssary after file data...
162. dos.writeBytes(lineEnd);
163. dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
164.
165. // close streams
166. fis.close();
167. dos.flush();
168. dos.close();
169. Log.e("fileUpload","File is written on the queue");
170.
171. } catch (MalformedURLException e) {
172. e.printStackTrace();
173. Toast.makeText(HttpUploader.this, "échec de connexion au site web ",
Toast.LENGTH_SHORT).show();
174. Log.i(getClass().getSimpleName(),"échec de connexion au site web 1");
175. } catch (IOException e) {
176. e.printStackTrace();
177. Toast.makeText(HttpUploader.this, "échec de connexion au site web ",
Toast.LENGTH_SHORT).show();
178. Log.i(getClass().getSimpleName(),"échec de connexion au site web 2");
…dauran.com/194-android-uploader-u… 4/6
31/01/2011 Android : uploader une image sur un s…
179. }
180.
181. //lecture de la réponse http
182. try {
183. BufferedReader rd = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
184. Log.i(getClass().getSimpleName(),"try HTTP reponse");
185. while ((httpResponse = rd.readLine()) != null) {
186. Log.i(getClass().getSimpleName(),"HTTP reponse= " + httpResponse);
187. if(httpResponse.contains("error")) {
188. //there is a http error
189. check += 1;
190. }
191. }
192. rd.close();
193. } catch (IOException ioex){
194. Log.e("HttpUploader", "error: " + ioex.getMessage(), ioex);
195. ioex.printStackTrace();
196. Toast.makeText(HttpUploader.this, "échec de lecture de la réponse du site web
", Toast.LENGTH_SHORT).show();
197. Log.i(getClass().getSimpleName(),"échec de lecture de la réponse du site web");
198. }
199.
200. }
201.
202. // Method called when the (instance of) the Service is requested to terminate
203. public void onDestroy() {
204. mUploadLooper.quit();
205.
206. if(check == 0) { //http response contains no error
207. Toast.makeText(HttpUploader.this, "photo envoyée", Toast.LENGTH_SHORT).show();
208. } else {
209. Toast.makeText(HttpUploader.this, "échec d'envoi de la photo",
Toast.LENGTH_SHORT).show();
210. }
211. super.onDestroy();
212. }
213.
214. @Override
215. public IBinder onBind(Intent intent) {
216. return null;
217. }
218.}
view sourceprint?
01.<?xml version="1.0" encoding="utf-8"?>
02.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03. android:orientation="vertical"
04. android:layout_width="fill_parent"
05. android:layout_height="fill_parent"
06. >
07.
08.<TextView
09. android:layout_width="fill_parent"
10. android:layout_height="wrap_content"
11. android:text="@string/hello"
12. />
13.
14. <Button
15. android:id="@+id/send"
16. android:layout_width="wrap_content"
17. android:layout_height="wrap_content"
18. android:layout_marginTop="10px"
19. android:text="Envoi" />
…dauran.com/194-android-uploader-u… 5/6
31/01/2011 Android : uploader une image sur un s…
20.</LinearLayout>
A vous de jouer !
…dauran.com/194-android-uploader-u… 6/6