android對於上傳文件,還是很簡單的,和java裡面的上傳都是一樣的,基本上都是熟悉操作輸出流和輸入流!還有一個特別重要的就是需要一些content-type這些參數的配置! 如果這些都弄好了,上傳就很簡單了! 下面是我寫的一個上傳的工具類:
[java] view plaincopy
- 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:[email protected]
- * QQ:840950105
- * MyName:石明政
- */
- public class UploadUtil {
- private static final String TAG = "uploadFile";
- private static final int TIME_OUT = 10*1000; //超時時間
- private static final String CHARSET = "utf-8"; //設置編碼
- /**
- * android上傳文件到服務器
- * @param file 需要上傳的文件
- * @param RequestURL 請求的rul
- * @return 返回響應的內容
- */
- public static String uploadFile(File file,String RequestURL)
- {
- String result = null;
- String BOUNDARY = UUID.randomUUID().toString(); //邊界標識 隨機生成
- String PREFIX = "--" , LINE_END = "\r\n";
- String CONTENT_TYPE = "multipart/form-data"; //內容類型
-
- 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); //設置編碼
- conn.setRequestProperty("connection", "keep-alive");
- conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
-
- if(file!=null)
- {
- /**
- * 當文件不為空,把文件包裝並且上傳
- */
- DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
- StringBuffer sb = new StringBuffer();
- sb.append(PREFIX);
- sb.append(BOUNDARY);
- sb.append(LINE_END);
- /**
- * 這裡重點注意:
- * name裡面的值為服務器端需要key 只有這個key 才可以得到對應的文件
- * 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();
- /**
- * 獲取響應碼 200=成功
- * 當響應成功,獲取響應的流
- */
- 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;
- }
- }
[java] view plain copy
- 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:[email protected]
- * QQ:840950105
- * MyName:石明政
- */
- public class UploadUtil {
- private static final String TAG = "uploadFile";
- private static final int TIME_OUT = 10*1000; //超時時間
- private static final String CHARSET = "utf-8"; //設置編碼
- /**
- * android上傳文件到服務器
- * @param file 需要上傳的文件
- * @param RequestURL 請求的rul
- * @return 返回響應的內容
- */
- public static String uploadFile(File file,String RequestURL)
- {
- String result = null;
- String BOUNDARY = UUID.randomUUID().toString(); //邊界標識 隨機生成
- String PREFIX = "--" , LINE_END = "\r\n";
- String CONTENT_TYPE = "multipart/form-data"; //內容類型
-
- 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); //設置編碼
- conn.setRequestProperty("connection", "keep-alive");
- conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
-
- if(file!=null)
- {
- /**
- * 當文件不為空,把文件包裝並且上傳
- */
- DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
- StringBuffer sb = new StringBuffer();
- sb.append(PREFIX);
- sb.append(BOUNDARY);
- sb.append(LINE_END);
- /**
- * 這裡重點注意:
- * name裡面的值為服務器端需要key 只有這個key 才可以得到對應的文件
- * 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();
- /**
- * 獲取響應碼 200=成功
- * 當響應成功,獲取響應的流
- */
- 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;
- }
- }
參數就一個File文件和一個請求上傳的URL,不過需要注意的是 ,因為需要用到了網絡請求,所以大家可不要忘記在上傳的時候,給android客戶端加一個訪問王珞丹呃權限哦!
還有一點就是需要大家注意一下:本人是做服務器端javaEE的,我發現在上傳的過程中,如果文件的標識name是java關鍵字之類的,上傳過程中,會存在很多位置的問題的!所以大家經可能的不要使用關鍵字哦!
下面是Activity的代碼:
[java] view plaincopy
- 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:[email protected]
- * QQ:840950105
- * MyName:石明政
- *
- */
- public class MainActivity extends Activity implements OnClickListener{
- private static final String TAG = "uploadImage";
- private static String requestURL = "http://192.168.1.14:8080/SetBlobData/img!up";
- private Button selectImage,uploadImage;
- private ImageView imageView;
-
- private String picPath = null;
-
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- selectImage = (Button) this.findViewById(R.id.selectImage);
- uploadImage = (Button) this.findViewById(R.id.uploadImage);
- selectImage.setOnClickListener(this);
- uploadImage.setOnClickListener(this);
-
- imageView = (ImageView) this.findViewById(R.id.imageView);
-
-
- }
-
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.selectImage:
- /***
- * 這個是調用android內置的intent,來過濾圖片文件 ,同時也可以過濾其他的
- */
- Intent intent = new Intent();
- intent.setType("image/*");
- intent.setAction(Intent.ACTION_GET_CONTENT);
- startActivityForResult(intent, 1);
- break;
- case R.id.uploadImage:
- File file = new File(picPath);
- if(file!=null)
- {
- String request = UploadUtil.uploadFile( file, requestURL);
- uploadImage.setText(request);
- }
- break;
- default:
- break;
- }
- }
-
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if(resultCode==Activity.RESULT_OK)
- {
- /**
- * 當選擇的圖片不為空的話,在獲取到圖片的途徑
- */
- Uri uri = data.getData();
- Log.e(TAG, "uri = "+ uri);
- try {
- String[] pojo = {MediaStore.Images.Media.DATA};
-
- Cursor cursor = managedQuery(uri, pojo, null, null,null);
- if(cursor!=null)
- {
- ContentResolver cr = this.getContentResolver();
- int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
- cursor.moveToFirst();
- String path = cursor.getString(colunm_index);
- /***
- * 這裡加這樣一個判斷主要是為了第三方的軟件選擇,比如:使用第三方的文件管理器的話,你選擇的文件就不一定是圖片了,這樣的話,我們判斷文件的後綴名
- * 如果是圖片格式的話,那麼才可以
- */
- if(path.endsWith("jpg")||path.endsWith("png"))
- {
- picPath = path;
- Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
- imageView.setImageBitmap(bitmap);
- }else{alert();}
- }else{alert();}
-
- } catch (Exception e) {
- }
- }
-
- super.onActivityResult(requestCode, resultCode, data);
- }
-
- private void alert()
- {
- Dialog dialog = new AlertDialog.Builder(this)
- .setTitle("提示")
- .setMessage("您選擇的不是有效的圖片")
- .setPositiveButton("確定",
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog,
- int which) {
- picPath = null;
- }
- })
- .create();
- dialog.show();
- }
-
- }
[java] view plain copy
- 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:[email protected]
- * QQ:840950105
- * MyName:石明政
- *
- */
- public class MainActivity extends Activity implements OnClickListener{
- private static final String TAG = "uploadImage";
- private static String requestURL = "http://192.168.1.14:8080/SetBlobData/img!up";
- private Button selectImage,uploadImage;
- private ImageView imageView;
-
- private String picPath = null;
-
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- selectImage = (Button) this.findViewById(R.id.selectImage);
- uploadImage = (Button) this.findViewById(R.id.uploadImage);
- selectImage.setOnClickListener(this);
- uploadImage.setOnClickListener(this);
-
- imageView = (ImageView) this.findViewById(R.id.imageView);
-
-
- }
-
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.selectImage:
- /***
- * 這個是調用android內置的intent,來過濾圖片文件 ,同時也可以過濾其他的
- */
- Intent intent = new Intent();
- intent.setType("image/*");
- intent.setAction(Intent.ACTION_GET_CONTENT);
- startActivityForResult(intent, 1);
- break;
- case R.id.uploadImage:
- File file = new File(picPath);
- if(file!=null)
- {
- String request = UploadUtil.uploadFile( file, requestURL);
- uploadImage.setText(request);
- }
- break;
- default:
- break;
- }
- }
-
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if(resultCode==Activity.RESULT_OK)
- {
- /**
- * 當選擇的圖片不為空的話,在獲取到圖片的途徑
- */
- Uri uri = data.getData();
- Log.e(TAG, "uri = "+ uri);
- try {
- String[] pojo = {MediaStore.Images.Media.DATA};
-
- Cursor cursor = managedQuery(uri, pojo, null, null,null);
- if(cursor!=null)
- {
- ContentResolver cr = this.getContentResolver();
- int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
- cursor.moveToFirst();
- String path = cursor.getString(colunm_index);
- /***
- * 這裡加這樣一個判斷主要是為了第三方的軟件選擇,比如:使用第三方的文件管理器的話,你選擇的文件就不一定是圖片了,這樣的話,我們判斷文件的後綴名
- * 如果是圖片格式的話,那麼才可以
- */
- if(path.endsWith("jpg")||path.endsWith("png"))
- {
- picPath = path;
- Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
- imageView.setImageBitmap(bitmap);
- }else{alert();}
- }else{alert();}
-
- } catch (Exception e) {
- }
- }
-
- super.onActivityResult(requestCode, resultCode, data);
- }
-
- private void alert()
- {
- Dialog dialog = new AlertDialog.Builder(this)
- .setTitle("提示")
- .setMessage("您選擇的不是有效的圖片")
- .setPositiveButton("確定",
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog,
- int which) {
- picPath = null;
- }
- })
- .create();
- dialog.show();
- }
-
- }
layout代碼:
[html] view plaincopy
- <?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"
- >
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="選擇圖片"
- android:id="@+id/selectImage"
- />
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="上傳圖片"
- android:id="@+id/uploadImage"
- />
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/imageView"
- />
- </LinearLayout>
[html] view plain copy
- <?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"
- >
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="選擇圖片"
- android:id="@+id/selectImage"
- />
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="上傳圖片"
- android:id="@+id/uploadImage"
- />
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/imageView"
- />
- </LinearLayout>
以上就是android 上傳圖片的全部代碼,如果想上傳其他文件的話,可以修改過濾條件就可以了,同時文件的類型一定要和服務器端的文件類型保持一致,否則上傳就失敗了!