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 | 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:vipa1888@163.com 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的代码:
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 | 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:vipa1888@163.com QQ:840950105 MyName:石明政 * */ public class MainActivity extends Activity implements OnClickListener { private static final String TAG = "uploadImage" ; 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代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <? xml version = "1.0" encoding = "utf-8" ?> android:orientation = "vertical" android:layout_width = "fill_parent" android:layout_height = "fill_parent" > < Button android:id = "@+id/selectImage" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:text = "选择图片" /> < Button android:id = "@+id/uploadImage" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:text = "上传图片" /> < ImageView android:id = "@+id/imageView" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </ LinearLayout > |
以上就是android上传图片的全部代码,如果想上传其他文件的话,可以修改过滤条件就可以了,同时文件的类型一定要和服务器端的文件类型保持一致,否则上传就失败了!
如果大家还有在使用过程中,发现有什么问题可以联系我!