android上传文件到服务器

android对于上传文件,还是很简单的,和java里面的上传都是一样的,基本上都是熟悉操作输出流和输入流!还有一个特别重要的就是需要一些 content-type这些参数的配置!  如果这些都弄好了,上传就很简单了!   下面是我写的一个上传的工具类:

001 package com.spring.sky.image.upload.network;
002   
003 import java.io.DataOutputStream;
004 import java.io.File;
005 import java.io.FileInputStream;
006 import java.io.IOException;
007 import java.io.InputStream;
008 import java.net.HttpURLConnection;
009 import java.net.MalformedURLException;
010 import java.net.URL;
011 import java.util.UUID;
012   
013 import android.util.Log;
014   
015 /**
016  
017  * 上传工具类
018  * @author spring sky
019  * Email:vipa1888@163.com
020  * QQ:840950105
021  * MyName:石明政
022  */
023 public class UploadUtil {
024     private static final String TAG = "uploadFile";
025     private static final int TIME_OUT = 10*1000;   //超时时间
026     private static final String CHARSET = "utf-8"; //设置编码
027     /**
028      * android上传文件到服务器
029      * @param file  需要上传的文件
030      * @param RequestURL  请求的rul
031      * @return  返回响应的内容
032      */
033     public static String uploadFile(File file,String RequestURL)
034     {
035         String result = null;
036         String  BOUNDARY =  UUID.randomUUID().toString();  //边界标识   随机生成
037         String PREFIX = "--" , LINE_END = "\r\n"
038         String CONTENT_TYPE = "multipart/form-data";   //内容类型
039           
040         try {
041             URL url = new URL(RequestURL);
042             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
043             conn.setReadTimeout(TIME_OUT);
044             conn.setConnectTimeout(TIME_OUT);
045             conn.setDoInput(true);  //允许输入流
046             conn.setDoOutput(true); //允许输出流
047             conn.setUseCaches(false);  //不允许使用缓存
048             conn.setRequestMethod("POST");  //请求方式
049             conn.setRequestProperty("Charset", CHARSET);  //设置编码
050             conn.setRequestProperty("connection", "keep-alive");   
051             conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); 
052               
053             if(file!=null)
054             {
055                 /**
056                  * 当文件不为空,把文件包装并且上传
057                  */
058                 DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
059                 StringBuffer sb = new StringBuffer();
060                 sb.append(PREFIX);
061                 sb.append(BOUNDARY);
062                 sb.append(LINE_END);
063                 /**
064                  * 这里重点注意:
065                  * name里面的值为服务器端需要key   只有这个key 才可以得到对应的文件
066                  * filename是文件的名字,包含后缀名的   比如:abc.png  
067                  */
068                   
069                 sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END); 
070                 sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
071                 sb.append(LINE_END);
072                 dos.write(sb.toString().getBytes());
073                 InputStream is = new FileInputStream(file);
074                 byte[] bytes = new byte[1024];
075                 int len = 0;
076                 while((len=is.read(bytes))!=-1)
077                 {
078                     dos.write(bytes, 0, len);
079                 }
080                 is.close();
081                 dos.write(LINE_END.getBytes());
082                 byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
083                 dos.write(end_data);
084                 dos.flush();
085                 /**
086                  * 获取响应码  200=成功
087                  * 当响应成功,获取响应的流  
088                  */
089                 int res = conn.getResponseCode();  
090                 Log.e(TAG, "response code:"+res);
091 //              if(res==200)
092 //              {
093                     Log.e(TAG, "request success");
094                     InputStream input =  conn.getInputStream();
095                     StringBuffer sb1= new StringBuffer();
096                     int ss ;
097                     while((ss=input.read())!=-1)
098                     {
099                         sb1.append((char)ss);
100                     }
101                     result = sb1.toString();
102                     Log.e(TAG, "result : "+ result);
103 //              }
104 //              else{
105 //                  Log.e(TAG, "request error");
106 //              }
107             }
108         } catch (MalformedURLException e) {
109             e.printStackTrace();
110         } catch (IOException e) {
111             e.printStackTrace();
112         }
113         return result;
114     }
115 }

参数就一个File文件和一个请求上传的URL,不过需要注意的是   ,因为需要用到了网络请求,所以大家可不要忘记在上传的时候,给android客户端加一个访问王珞丹呃权限哦!  

 还有一点就是需要大家注意一下:本人是做服务器端javaEE的,我发现在上传的过程中,如果文件的标识name是java关键字之类的,上传过程中,会存在很多位置的问题的!所以大家经可能的不要使用关键字哦!

下面是Activity的代码:

001 package com.spring.sky.image.upload;
002   
003   
004 import java.io.File;
005   
006 import com.spring.sky.image.upload.network.UploadUtil;
007   
008 import android.app.Activity;
009 import android.app.AlertDialog;
010 import android.app.Dialog;
011 import android.content.ContentResolver;
012 import android.content.DialogInterface;
013 import android.content.Intent;
014 import android.database.Cursor;
015 import android.graphics.Bitmap;
016 import android.graphics.BitmapFactory;
017 import android.net.Uri;
018 import android.os.Bundle;
019 import android.provider.MediaStore;
020 import android.util.Log;
021 import android.view.View;
022 import android.view.View.OnClickListener;
023 import android.widget.Button;
024 import android.widget.ImageView;
025 /**
026  * Activity 上传的界面
027  * @author spring sky
028  * Email:vipa1888@163.com
029  * QQ:840950105
030  * MyName:石明政
031  *
032  */
033 public class MainActivity extends Activity implements OnClickListener{
034     private static final String TAG = "uploadImage";
035     private static String requestURL = "http://192.168.1.14:8080/SetBlobData/img!up";
036     private Button selectImage,uploadImage;
037     private ImageView imageView;
038       
039     private String picPath = null;
040       
041     /** Called when the activity is first created. */
042     @Override
043     public void onCreate(Bundle savedInstanceState) {
044         super.onCreate(savedInstanceState);
045         setContentView(R.layout.main);
046           
047         selectImage = (Button) this.findViewById(R.id.selectImage);
048         uploadImage = (Button) this.findViewById(R.id.uploadImage);
049         selectImage.setOnClickListener(this);
050         uploadImage.setOnClickListener(this);
051           
052         imageView = (ImageView) this.findViewById(R.id.imageView);
053           
054           
055     }
056       
057     @Override
058     public void onClick(View v) {
059         switch (v.getId()) {
060         case R.id.selectImage:
061             /***
062              * 这个是调用android内置的intent,来过滤图片文件   ,同时也可以过滤其他的  
063              */
064             Intent intent = new Intent();
065             intent.setType("image/*");
066             intent.setAction(Intent.ACTION_GET_CONTENT);
067             startActivityForResult(intent, 1);
068             break;
069         case R.id.uploadImage:
070             File file = new File(picPath);
071             if(file!=null)
072             {
073                 String request = UploadUtil.uploadFile( file, requestURL);
074                 uploadImage.setText(request);
075             }
076             break;
077         default:
078             break;
079         }
080     }
081   
082     @Override
083     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
084         if(resultCode==Activity.RESULT_OK)
085         {
086             /**
087              * 当选择的图片不为空的话,在获取到图片的途径  
088              */
089             Uri uri = data.getData();
090             Log.e(TAG, "uri = "+ uri);
091             try {
092                 String[] pojo = {MediaStore.Images.Media.DATA};
093                   
094                 Cursor cursor = managedQuery(uri, pojo, null, null,null);
095                 if(cursor!=null)
096                 {
097                     ContentResolver cr = this.getContentResolver();
098                     int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
099                     cursor.moveToFirst();
100                     String path = cursor.getString(colunm_index);
101                     /***
102                      * 这里加这样一个判断主要是为了第三方的软件选择,比如:使用第三方的文件管理器的话,你选择的文件就不一定是图片了,这样的话,我们判断文件的后缀名
103                      * 如果是图片格式的话,那么才可以   
104                      */
105                     if(path.endsWith("jpg")||path.endsWith("png"))
106                     {
107                         picPath = path;
108                         Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
109                         imageView.setImageBitmap(bitmap);
110                     }else{alert();}
111                 }else{alert();}
112                   
113             } catch (Exception e) {
114             }
115         }
116           
117         super.onActivityResult(requestCode, resultCode, data);
118     }
119       
120     private void alert()
121     {
122         Dialog dialog = new AlertDialog.Builder(this)
123         .setTitle("提示")
124         .setMessage("您选择的不是有效的图片")
125         .setPositiveButton("确定",
126                 new DialogInterface.OnClickListener() {
127                     public void onClick(DialogInterface dialog,
128                             int which) {
129                         picPath = null;
130                     }
131                 })
132         .create();
133         dialog.show();
134     }
135       
136 }

layout代码:

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     <Button  
08     android:layout_width="fill_parent" 
09     android:layout_height="wrap_content" 
10     android:text="选择图片"
11     android:id="@+id/selectImage"
12     />
13     <Button  
14     android:layout_width="fill_parent" 
15     android:layout_height="wrap_content" 
16     android:text="上传图片"
17     android:id="@+id/uploadImage"
18     />
19      <ImageView  
20     android:layout_width="wrap_content" 
21     android:layout_height="wrap_content" 
22     android:id="@+id/imageView"
23     />
24 </LinearLayout>

以上就是android 上传图片的全部代码,如果想上传其他文件的话,可以修改过滤条件就可以了,同时文件的类型一定要和服务器端的文件类型保持一致,否则上传就失败了!

posted @ 2012-09-18 10:49  郑文亮  阅读(1267)  评论(0编辑  收藏  举报