zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

android上传文件到服务器代码实例

2023-06-13 09:15:13 时间

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

复制代码代码如下:

packagecom.spring.sky.image.upload.network;

importjava.io.DataOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.MalformedURLException;
importjava.net.URL;
importjava.util.UUID;

importandroid.util.Log;

/**
 *
 *上传工具类
 *@authorspringsky
 *Email:vipa1888@163.com
 *QQ:840950105
 *MyName:石明政
 */
publicclassUploadUtil{
   privatestaticfinalStringTAG="uploadFile";
   privatestaticfinalintTIME_OUT=10*1000;  //超时时间
   privatestaticfinalStringCHARSET="utf-8";//设置编码
   /**
    *android上传文件到服务器
    *@paramfile 需要上传的文件
    *@paramRequestURL 请求的rul
    *@return 返回响应的内容
    */
   publicstaticStringuploadFile(Filefile,StringRequestURL)
   {
       Stringresult=null;
       String BOUNDARY= UUID.randomUUID().toString(); //边界标识  随机生成
       StringPREFIX="--",LINE_END="\r\n";
       StringCONTENT_TYPE="multipart/form-data";  //内容类型

       try{
           URLurl=newURL(RequestURL);
           HttpURLConnectionconn=(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)
           {
               /**
                *当文件不为空,把文件包装并且上传
                */
               DataOutputStreamdos=newDataOutputStream(conn.getOutputStream());
               StringBuffersb=newStringBuffer();
               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());
               InputStreamis=newFileInputStream(file);
               byte[]bytes=newbyte[1024];
               intlen=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=成功
                *当响应成功,获取响应的流 
                */
               intres=conn.getResponseCode(); 
               Log.e(TAG,"responsecode:"+res);
//               if(res==200)
//               {
                   Log.e(TAG,"requestsuccess");
                   InputStreaminput= conn.getInputStream();
                   StringBuffersb1=newStringBuffer();
                   intss;
                   while((ss=input.read())!=-1)
                   {
                       sb1.append((char)ss);
                   }
                   result=sb1.toString();
                   Log.e(TAG,"result:"+result);
//               }
//               else{
//                   Log.e(TAG,"requesterror");
//               }
           }
       }catch(MalformedURLExceptione){
           e.printStackTrace();
       }catch(IOExceptione){
           e.printStackTrace();
       }
       returnresult;
   }
}

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


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

下面是Activity的代码:

复制代码代码如下:


packagecom.spring.sky.image.upload;


importjava.io.File;

importcom.spring.sky.image.upload.network.UploadUtil;

importandroid.app.Activity;
importandroid.app.AlertDialog;
importandroid.app.Dialog;
importandroid.content.ContentResolver;
importandroid.content.DialogInterface;
importandroid.content.Intent;
importandroid.database.Cursor;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.provider.MediaStore;
importandroid.util.Log;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.ImageView;
/**
 *Activity上传的界面
 *@authorspringsky
 *Email:vipa1888@163.com
 *QQ:840950105
 *MyName:石明政
 *
 */
publicclassMainActivityextendsActivityimplementsOnClickListener{
   privatestaticfinalStringTAG="uploadImage";
   privatestaticStringrequestURL="http://192.168.1.14:8080/SetBlobData/img!up";
   privateButtonselectImage,uploadImage;
   privateImageViewimageView;

   privateStringpicPath=null;

   /**Calledwhentheactivityisfirstcreated.*/
   @Override
   publicvoidonCreate(BundlesavedInstanceState){
       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
   publicvoidonClick(Viewv){
       switch(v.getId()){
       caseR.id.selectImage:
           /***
            *这个是调用android内置的intent,来过滤图片文件  ,同时也可以过滤其他的 
            */
           Intentintent=newIntent();
           intent.setType("image/*");
           intent.setAction(Intent.ACTION_GET_CONTENT);
           startActivityForResult(intent,1);
           break;
       caseR.id.uploadImage:
           Filefile=newFile(picPath);
           if(file!=null)
           {
               Stringrequest=UploadUtil.uploadFile(file,requestURL);
               uploadImage.setText(request);
           }
           break;
       default:
           break;
       }
   }

   @Override
   protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
       if(resultCode==Activity.RESULT_OK)
       {
           /**
            *当选择的图片不为空的话,在获取到图片的途径 
            */
           Uriuri=data.getData();
           Log.e(TAG,"uri="+uri);
           try{
               String[]pojo={MediaStore.Images.Media.DATA};

               Cursorcursor=managedQuery(uri,pojo,null,null,null);
               if(cursor!=null)
               {
                   ContentResolvercr=this.getContentResolver();
                   intcolunm_index=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                   cursor.moveToFirst();
                   Stringpath=cursor.getString(colunm_index);
                   /***
                    *这里加这样一个判断主要是为了第三方的软件选择,比如:使用第三方的文件管理器的话,你选择的文件就不一定是图片了,这样的话,我们判断文件的后缀名
                    *如果是图片格式的话,那么才可以  
                    */
                   if(path.endsWith("jpg")||path.endsWith("png"))
                   {
                       picPath=path;
                       Bitmapbitmap=BitmapFactory.decodeStream(cr.openInputStream(uri));
                       imageView.setImageBitmap(bitmap);
                   }else{alert();}
               }else{alert();}

           }catch(Exceptione){
           }
       }

       super.onActivityResult(requestCode,resultCode,data);
   }

   privatevoidalert()
   {
       Dialogdialog=newAlertDialog.Builder(this)
       .setTitle("提示")
       .setMessage("您选择的不是有效的图片")
       .setPositiveButton("确定",
               newDialogInterface.OnClickListener(){
                   publicvoidonClick(DialogInterfacedialog,
                           intwhich){
                       picPath=null;
                   }
               })
       .create();
       dialog.show();
   }

}

layout代码:

复制代码代码如下:
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns: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上传图片的全部代码,如果想上传其他文件的话,可以修改过滤条件就可以了,同时文件的类型一定要和服务器端的文件类型保持一致,否则上传就失败了!