Android 上传图片到服务器 okhttp一

移动开发 作者: 2024-08-24 16:05:01
【目录】 (一)上传图片到服务器一 Android代码 (二)上传图片到服务器二 Android 系统7.0以上调用相机兼容问题 (三)上传图片到服务器三 后台服务器代码 一、相关知识 ①Androi

 【目录】

一、相关知识

二、效果展示

二、代码

 1          <LinearLayout
 2                 android:layout_width="match_parent"
 3                 android:layout_height="wrap_content"
 4                 android:orientation="vertical"
 5                 android:background="@color/white"
 6                 >
 7                 android.support.v7.widget.RecyclerView
 8                     android:id="@+id/rvPic"
 9                     android:layout_width10                     android:layout_height11                     android:layout_gravity="center_horizontal"12 
13                 </android.support.v7.widget.RecyclerView14 
15                 TextView
16                     ="@+id/tvNum"
17 18 19                     android:text="0/8"
20                     android:textColor="#666666"
21 ="right|bottom"
22                     android:paddingRight="@dimen/dp_10"/>
23 
24 
25             LinearLayout26      Button
27 
28         ="@+id/btn_Enter"
29         android:layout_width30         android:layout_height="@dimen/dp_45"
31         android:layout_alignParentBottom="true"
32         android:background="@drawable/selecter_button"
33         android:text="确认上传"
34         android:textColor="@color/inButtonText"
35         android:textSize="@dimen/dp_18" />
 1 public class LoadFileVo {
 2 
 3     File file;
 4 
 5     int pg; //图片下方的进度条
 6 
 7     boolean isUpload = false; 标识该文件是否上传
 8 
 9     Bitmap bitmap;
10 
11     public Bitmap getBitmap() {
12         return bitmap;
13     }
15     void setBitmap(Bitmap bitmap) {
16         this.bitmap =17 18 
19     boolean isUpload() {
20          isUpload;
21 22 
23     void setUpload( upload) {
24         isUpload = upload;
25 26 
27      LoadFileVo() {
28 29 
30     public LoadFileVo(File file,int pg) {
31         this.file = file;
32         this.pg = pg;
33 34 
35     boolean isUpload,1)"> pg,Bitmap bitmap) {
36         37         38         this.isUpload =39         40 41 
42      File getFile() {
43         44 45 
46      setFile(File file) {
47         48 49 
50      getPg() {
51         52 53 
54     void setPg(55         56 57 }
  1 /*
  2  *Create By 小群子    2018/12/10
  3  */
  4 
  5 class LoadPicAdapter extends RecyclerView.Adapter<LoadPicAdapter.MyViewHolder> {
  6 
  7     Context context;
  8     List<LoadFileVo> fileList = null;
  9     View view;
 10     int picNum = 8;列表的图片个数最大值
 11 
 12     public LoadPicAdapter(Context context,List<LoadFileVo> fileList) {
 13         this.context = context;
 14         this.fileList = fileList;
 15  16 
 17      picNum) {
 18          19          20         this.picNum = picNum;
 21  22 
 23     interface OnItemClickListener {
 24         void click(View view,1)"> positon);
 25 
 26          del(View view);
 27  28 
 29     OnItemClickListener listener;
 30 
 31      setListener(OnItemClickListener listener) {
 32         this.listener = listener;
 33  34 
 35     @Override
 36     public MyViewHolder onCreateViewHolder(ViewGroup parent,1)"> viewType) {
 37 
 38         view = LayoutInflater.from(context).inflate(R.layout.load_item_pic,parent,1)">false);
 39         return new MyViewHolder(view);
 40  41 
 42  43     void onBindViewHolder(MyViewHolder holder,1)">final  position) {
 44 
 45         通过默认设置第一个为空文件为添加退保,且在文件个数小于最大限制值的情况。当图片个数等于最大限制值,第一个则不是添加按钮
 46         if (position == 0&&fileList.get(position).getBitmap()==) {
 47             holder.ivPic.setImageResource(R.drawable.addpic);加号图片
 48             holder.ivPic.setOnClickListener( View.OnClickListener() {
 49                 @Override
 50                  onClick(View view) {
 51                     listener.click(view,position);
 52                 }
 53             });
 54             holder.ivDel.setVisibility(View.INVISIBLE);
 55             holder.bg_progressbar.setVisibility(View.GONE);
 56 
 57         } else 58             Uri uri = Uri.parse(fileList.get(position).getFile().getPath());
 59             holder.ivPic.setImageURI(uri);
 60 
 61             holder.ivPic.setImageBitmap(fileList.get(position).getBitmap());
 62             使用压缩后的图片进行填充到界面上
 63            
64 65 66 holder.ivDel.setVisibility(View.VISIBLE); 67 holder.bg_progressbar.setVisibility(View.VISIBLE); 68 holder.bg_progressbar.setProgress(fileList.get(position).getPg()); 69 } 70 71 72 holder.ivDel.setOnClickListener( 73 @Override 74 75 判断图片是否上传,上传后将无法删除 76 if (fileList.get(position).isUpload()) { 77 Toast.makeText(context,"该图片已上传!",Toast.LENGTH_SHORT).show(); 78 } 79 fileList.remove(position); 80 if (fileList.size()==picNum-1&&fileList.get(0).getBitmap()!=){ 81 fileList.add(0,1)"> LoadFileVo()); 82 }如果数量达到最大数时,前面的加号去掉,然后再减去时,则添加前面的加号 83 notifyDataSetChanged(); 84 if (listener!= 85 listener.del(view);传递接口,计算图片个数显示在界面中 86 } 87 88 89 } 90 }); 91 92 93 94 95 96 getItemCount() { 97 fileList.size(); 98 99 100 101 static class MyViewHolder extends RecyclerView.ViewHolder { 102 @BindView(R.id.ivPic) 103 ImageView ivPic; 104 @BindView(R.id.ivDel) 105 ImageView ivDel; 106 @BindView(R.id.bg_progressbar) 107 ProgressBar bg_progressbar; 108 109 View view; 110 111 112 MyViewHolder(View view) { 113 super(view); 114 this.view = view; 115 ButterKnife.bind(this116 117 118 }
 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     android:layout_width="@dimen/dp_110"
 3     android:layout_height="@dimen/dp_115"
 5     >
 7     < 8         android:layout_width="match_parent"
 9         android:layout_height="match_parent"
10         android:orientation="vertical"
11         android:padding="@dimen/dp_5">
13         <ImageView
14             android:id="@+id/ivPic"
15             android:layout_width="match_parent"
16             android:layout_height="@dimen/dp_100"
17             android:scaleType="centerCrop"
18             android:src="@drawable/ic_pick"
19             />
20 
21         <ProgressBar
22             android:id="@+id/bg_progressbar"
23             style="@style/StyleProgressBarMini"
24             android:layout_width="match_parent"
25             android:layout_height="@dimen/dp_5"
26             android:background="@drawable/shape_progressbar_mini"
27             android:max="100"
28             android:progress="60" />
29     </LinearLayout>
30     <31         android:id="@+id/ivDel"
32         android:layout_width="@dimen/dp_25"
33         android:layout_height="@dimen/dp_25"
34         android:src="@drawable/delete_round"
35         android:layout_alignParentRight="true"/>
36 
37 </RelativeLayout>
 1 List<LoadFileVo> fileList = new ArrayList<>();
 2 LoadPicAdapter adapter =  3 
 4   这里使用ButterKnife
 5     @BindView(R.id.rvPic)
 6       RecyclerView rvPic;
 7 
 8     @BindView(R.id.tvNum)
       TextView tvNum;
11 
12     初始化Adapter
13     设置图片选择的接口
14     private  initAdapter() {
15         fileList.add(16         adapter = new LoadPicAdapter(this,fileList,8        rvPic.setAdapter(adapter);
18         rvPic.setLayoutManager(new GridLayoutManager());
19         adapter.setListener( LoadPicAdapter.OnItemClickListener() {
20 21              positon) {
22                 if (fileList.size()>823                     showShortToast("一次最多上传8张图片!"24                 }25                     selectPic();  选择添加图片方法
26 30 31              del(View view) {
32                 tvNum.setText((fileList.size()-1)+"/8"34 35     }
String mPhtotPath;
 2 Uri uriImage;
 3 File mPhotoFile =  5 
选择图片
 7  selectPic() {
动态请求权限,除此之外还需进行Androidmanifest.xml中进行请求
11         if (ContextCompat.checkSelfPermission(12                 != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(13                 Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
14                 || ContextCompat.checkSelfPermission(15                 Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
16             ActivityCompat.requestPermissions(17                      String[]{Manifest.permission.CAMERA,1)">18                             Manifest.permission.READ_EXTERNAL_STORAGE,1)">19                             Manifest.permission.WRITE_EXTERNAL_STORAGE},1)">20                     124         final CharSequence[] items = {"相册","拍照"};
25         AlertDialog.Builder dlg = new AlertDialog.Builder(EndLoadMstActivity.26         dlg.setTitle("添加图片"27         dlg.setItems(items,1)"> DialogInterface.OnClickListener() {
28             void onClick(DialogInterface dialog,1)"> item) {
29                  这里item是根据选择的方式,
30                 if (item == 031                     Intent intent =  Intent(Intent.ACTION_PICK);
32                     intent.setType("image/*"33                     startActivityForResult(intent,034                 } 35                     try36                         Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"37                         mPhtotPath = getSDPath() + "/" + getPhotoFileName();
38                         mPhotoFile =  File(mPhtotPath);
39                         if (!mPhotoFile.exists()) {
                            mPhotoFile.createNewFile();
41                         }
42                         uriImage = FileProvider.getUriForFile(EndLoadMstActivity.this,getPackageName() + ".provider",createImageFile());
43 
44                         uriImage = FileProvider.getUriForFile(EndLoadMstActivity.45                         Log.i("TAG","onClick: "+mPhtotPath+"---------" + getPackageName() + ".provider"46                          uriImage = Uri.fromFile(mPhotoFile);以上一句代替解决相机兼容问题
47                         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,uriImage);
50                         startActivityForResult(intent,151 
52                     } catch (Exception e) {
53                         e.printStackTrace();
54 55 57         }).create();
58         dlg.show();
59 60 
61  String getSDPath() {
62         File sdDir = 63         boolean sdCardExsit = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
64          (sdCardExsit) {
65             sdDir = Environment.getExternalStorageDirectory();
66 67          sdDir.toString();
68 69 
70     private String getPhotoFileName() {
71         Date date =  Date(System.currentTimeMillis());
72         SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss"73         return dateFormat.format(date) + ".jpg"74     }
重写onActivityResult方法
@Override
 3     protected void onActivityResult(int requestCode,1)"> resultCode,Intent data) {
 4         .onActivityResult(requestCode,resultCode,data);
 5         if (requestCode == 1 6             BitmapFactory.Options options =  BitmapFactory.Options();
 7             options.inSampleSize = 2; 图片宽高都为原来的二分之一,即图片为原来的四分之一
 8             Bitmap bitmap = BitmapFactory.decodeFile(mPhtotPath,options);
 9             if (bitmap != 10                 if (uriImage != 11                     saveUritoFile(uriImage,1)">12 13 
14                 bitmap.isRecycled()) {
15                     bitmap.recycle(); 回收图片所占的内存
16                     System.gc(); 提醒系统及时回收
if (requestCode == 0if (data != 22                 Uri uri = data.getData();
23                 saveUritoFile(uri,1)">24 27 28 
29 将Uri图片类型转换成File,BitMap类型
在界面上显示BitMap图片,以防止内存溢出
31 上传可选择File文件上传
32 
33     void saveUritoFile(Uri uriImage,1)"> type) {
34         Bitmap photoBmp = 35 
37             38                 photoBmp = MediaStore.Images.Media.getBitmap(this.getContentResolver(),1)">39                 ByteArrayOutputStream fos = new ByteArrayOutputStream();
                photoBmp.compress(Bitmap.CompressFormat.JPEG,80,fos);
41                 以上代码压缩不行,还是会造成内存溢出
42 
43                 BitmapFactory.Options options = 44                 options.inSampleSize = 2; 45                 photoBmp = BitmapFactory.decodeStream(.getContentResolver()
46                         .openInputStream(uriImage),1)">47 
48                 File file = new File(""49                 if (type==050                     file = FileParseUtils.getFileByUri(52                 }53                     if (mPhotoFile!=54                         file = mPhotoFile;
56 
                File file = new File("");
                try {
60                     file = new File(new URI(uriImage.toString()));
                } catch (URISyntaxException e) {
62                     e.printStackTrace();
63                 }
64                 fileList.add(new LoadFileVo(file,1)">false,photoBmp));
65                 tvNum.setText((fileList.size()-1)+"/8"66                 ){    //判断时候达到最大数量,如果达到最大数量,则去掉前面的加号
67                     fileList.remove(070                 adapter.notifyDataSetChanged();
71 
72             }  (IOException e) {
73                 e.printStackTrace();
74                 Log.i("TAG","saveUritoFile: ---------压缩图片异常!"75 76 
77 
78 79 
80     }
一张张图片轮流上传
void netUpload(int i,1)">final String joData) {用jsonOject方式转string传递其他参数
  3           5             isRequestHttp) {
  6                 isRequestHttp = true  7                 int finalI = i;
  8                 enterEnable(  9 
 10                  (fileList.get(finalI).isUpload()) {
 11                     netUpload(finalI + 1 12                 }  13 
 14         RequestBody requestBody =  MultipartBody.Builder()
                .setType(MultipartBody.FORM)
 16                 .addFormDataPart("mstjson",msg)  其他信息
 17                 .addFormDataPart("file" 18                         RequestBody.create(MediaType.parse("application/octet-stream"),file))文件
 19                 .build();
 20         Request request =  Request.Builder()
 21                 .url(uploadPic---这里是图片上传的地址).post(requestBody)
 22  23         okHttpClient.newCall(request).enqueue( UICallBack() {
 24                         @Override
 25                          onFailureUI(Call call,IOException e) {
 26                             showShortToast("连接服务器失败" 27                             isRequestHttp =  28                             enterEnable( 29 
 30  31 
 32  33                          onResponseUI(Call call,Response response) {
 34                              35 
 36                                 isRequestHttp =  38                                 String result = response.body().string();
 39                                 Utils.log("上传图片结果:" + result);
 40 
 42                                 response.isSuccessful()) {
 43                                     Utils.log("响应失败:" + response.code());
 44                                     showShortToast("响应失败:" + 45                                     enterEnable( 46 
 47                                      48                                 }
 49                                 if (result.equals("{}")) {
 50                                     showShortToast("获取服务端数据为空" 51                                     enterEnable( 52 
 53                                      55                                 JSONObject jsonObject =  JSONObject(result);
 56                                 if (jsonObject.getString("IsError").equals("true" 57                                     showShortToast(jsonObject.getString("ErrMsg" 58                                     enterEnable( 59 
 60                                 }  61                                     String Data = jsonObject.getString("Data" 62                                     fileList.get(finalI).setPg(100 63                                     fileList.get(finalI).setUpload( 64                                     adapter.notifyDataSetChanged();
 66                                     if (finalI == fileList.size() - 1 67                                         showShortToast("上传成功!" 68 
 69                                         btnEnter.setText("已上传" 70                                        
 71                                     }  72                                         netUpload((finalI + 1),1)">                                    }
 74 
 75  76                             }  77                                 isRequestHttp =  78                                 hideLoadingDialog();
 79                                 showShortToast("上传凭证发生异常!" 80                                 LogToFile.e("上传凭证发生异常," + e);
 81                                 enterEnable( 82 
                            }
 84  85                     });
 86 
 87        }
 89         }  90             isRequestHttp =  91             hideLoadingDialog();
 93             showShortToast("上传图片请求异常!" 94             LogToFile.e("上传图片请求异常," + 95             enterEnable( 96 
 97 101 用来提示用户文件上传的情况。同时也是避免同时反复操作
void enterEnable( isEnabled) {
103          (isEnabled) {
104             btnEnter.setText("重新上传"105             btnEnter.setEnabled(            btnEnter.setBackgroundResource(R.drawable.selecter_button);
            btnEnter.setTextColor(getResources().getColor(R.color.inButtonText));
109         } 110             btnEnter.setText("正在上传···"111             btnEnter.setEnabled(            btnEnter.setBackgroundResource(R.drawable.buttonshap);
113             btnEnter.setTextColor(getResources().getColor(R.color.outButtonText));
114 115     }
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_67904.html