1. 程式人生 > >Android 多圖上傳伺服器_At_Swim

Android 多圖上傳伺服器_At_Swim


圖片我就不上傳了沒有好的圖片

MainActivity,佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android
:layout_height="match_parent" android:orientation="vertical" android:gravity="center" tools:context="com.example.lenovo.duotupian_demo.MainActivity"> <Button android:id="@+id/btnAddPhoto" android:layout_width="match_parent" android:layout_height="wrap_content"
android:text="上傳圖片"/>

</LinearLayout>

監聽

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btnAddPhoto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main
); initView(); } private void initView() { btnAddPhoto = (Button) findViewById(R.id.btnAddPhoto); btnAddPhoto.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnAddPhoto: startActivity(new Intent(MainActivity.this,UploadPhotoActivity.class)); break; } }

}


 

UploadPhotoActivity,佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context="com.example.lenovo.duotupian_demo.UploadPhotoActivity">

    <GridView
        android:id="@+id/mGradView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:numColumns="3"/>

    <Button
        android:id="@+id/btnOk"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="@color/colorAccent"
        android:text="選擇圖片"
        android:textColor="@android:color/white"/>
</LinearLayout>


UploadPhotoActivity


package com.example.lenovo.duotupian_demo;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;

public class UploadPhotoActivity extends AppCompatActivity implements View.OnClickListener {

    private GridView mGradView;
    private Button btnOk;
    private List<PhotoBean> mList;
    private GridAdapter adapter;
    private List<String> mListPath = new ArrayList<String>();
    private File file;
    private int count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_photo);
        initView();
        initData();
        initAdapter();
    }

    private void initAdapter() {
        adapter = new GridAdapter(this, mList);
        mGradView.setAdapter(adapter);
        initListener();
    }

    private void initListener() {
        mGradView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                count = 0;

                 mListPath.clear();
                 PhotoBean bean = mList.get(position);
                 bean.setSelect(!bean.isSelect());
                 //便利每個圖片
                 for (PhotoBean p : mList) {
                  
                     if (p.isSelect()) {
                         count++;
                         //  點選的圖片新增到集合
                         mListPath.add(p.getPath());
                     }
                 }
                 //只能新增9張圖片
                 if(count <= 9){
                     //重新整理介面卡
                     adapter.notifyDataSetChanged();
                     btnOk.setText(count + "/ 9 完成");
                 }else{
                     Toast.makeText(UploadPhotoActivity.this, "不能點了", Toast.LENGTH_SHORT).show();
                 }
            }

        });
    }

    private void initView() {
        mGradView = (GridView) findViewById(R.id.mGradView);
        btnOk = (Button) findViewById(R.id.btnOk);
        btnOk.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnOk:
                uploadFile();
                finish();
                break;
        }
    }
    private void uploadFile() {
        
        //OkHttp的依賴
        //          implementation 'com.squareup.okhttp3:okhttp:3.2.0'
        
        OkHttpClient client=new OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15,TimeUnit.SECONDS)
                .build();
        
        // Retrofit2.0的依賴
        //           compile 'com.squareup.retrofit2:retrofit:2.3.0'
        //           compile 'com.squareup.retrofit2:converter-gson:2.3.0'
        
        Retrofit build = new Retrofit.Builder()
                //伺服器路徑
                .baseUrl("伺服器路徑")
                .client(client)
                .build();
        APIService apiServices = build.create(APIService.class);
        //迴圈上傳圖片
        for (int i = 0; i < mListPath.size(); i++) {
            //圖片路徑 新增到 檔案裡
            file = new File(mListPath.get(i));
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("file", System.currentTimeMillis() + ".png", requestBody);
            retrofit2.Call<ResponseBody> responseBodyCall = apiServices.postFileUpload(part);
            responseBodyCall.enqueue(new retrofit2.Callback<ResponseBody>() {
                @Override
                public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                    try {
                        String string = response.body().string();
                        if(string != null){
                            Log.e("TAG", "onResponse: 有資料");
                        }else{
                            Log.e("TAG", "onResponse: 沒有資料");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {

                }
            });
        }



    }

    private void initData() {
        mList = new ArrayList<>();
        //獲取手機相簿圖片 
        ContentResolver mContentResolver = getContentResolver();
        //圖片資料的Uri(外部儲存)
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        //查詢
        Cursor cursor = mContentResolver.query(uri,null,null,null,null);
        //遍歷圖片
        while (cursor.moveToNext()){
            PhotoBean bean = new PhotoBean();
            //獲取圖片路徑
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            //設定圖片路徑
            bean.setPath(path);
            //預設fasle
            bean.setSelect(false);
            //新增圖片
            mList.add(bean);
        }
    }
}

 

GridView介面卡


 
package com.example.lenovo.duotupian_demo;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import java.util.List;

public class GridAdapter extends BaseAdapter {

    //資料
    private List<PhotoBean> mList;
    //佈局載入器
    private LayoutInflater mInflater;
    //實體類
    private PhotoBean bean;
    //上下文
    private Context mContext;
    //螢幕寬高
    private int w, h;
    
    public GridAdapter(Context mContext, List<PhotoBean> mList) {
        this.mContext = mContext;
        this.mList = mList;
        mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        getPhoneWH();
    }

  
    private void getPhoneWH() {
        //獲取手機螢幕高度
        w = mContext.getResources().getDisplayMetrics().widthPixels;
        h = mContext.getResources().getDisplayMetrics().heightPixels;
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int i) {
        return mList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder = null;
        if (view == null) {
            viewHolder = new ViewHolder();
            view = mInflater.inflate(R.layout.list_item, null);
            viewHolder.img = (ImageView) view.findViewById(R.id.img);
            //設定圖片最小寬高
            viewHolder.img.setMinimumWidth(w / 3);
            viewHolder.img.setMinimumHeight(h / 3);
            viewHolder.img_select = (ImageView) view.findViewById(R.id.img_select);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }

        //獲取position
        bean = mList.get(i);
        //是否選中
        if (bean.isSelect()) {
            viewHolder.img_select.setVisibility(View.VISIBLE);
        } else {
            viewHolder.img_select.setVisibility(View.INVISIBLE);
        }
        //是否有圖片
        if (bean.getBitmap() == null) {
            //圖片載入,非同步載入
            new ImgTask().execute(bean.getPath(), String.valueOf(i));
        } else {
            //設定圖片
            viewHolder.img.setImageBitmap(bean.getBitmap());
        }
        return view;
    }
    
    static class ViewHolder {
        private ImageView img;
        private ImageView img_select;
    }
    private class ImgTask extends AsyncTask<String, Void, Bitmap> {
        
        @Override
        protected Bitmap doInBackground(String... strings) {
            //圖片路徑
            String path = strings[0];
            //position
            int position = Integer.parseInt(strings[1]);
            //圖片壓縮
            Bitmap bitmap = BitmapUtils.getScaleBitmapPath(mContext, path);
            //設定圖片
            mList.get(position).setBitmap(bitmap);
            return bitmap;
        }
        
        //重新整理檢視
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            //重新整理
            GridAdapter.this.notifyDataSetChanged();
        }
    }
}

list_item 佈局


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="100dp">

   <FrameLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content">

       <ImageView
           android:id="@+id/img"
           android:src="@mipmap/ic_launcher"
           android:layout_width="wrap_content"
           android:layout_height="120dp"
           android:scaleType="fitXY"/>

       <ImageView
           android:id="@+id/img_select"
           android:src="@mipmap/personal_check_img"
           android:visibility="invisible"
         android:layout_gravity="right"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content" />
   </FrameLayout>
</LinearLayout>

  

BitmapUtils 工具


package com.example.lenovo.duotupian_demo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class BitmapUtils {

    /**
     * 本地圖片壓縮處理
     *
     * @param mContext 上下文
     * @param path     路徑
     * @return
     */
    public static Bitmap getScaleBitmapPath(Context mContext, String path) {
        Bitmap bitmap;
        int w;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        bitmap = BitmapFactory.decodeFile(path, options);
        w = options.outWidth;
        if (w < 50) {
            options.inSampleSize = w / 50;
            options.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeFile(path, options);
        } else {
            bitmap = BitmapFactory.decodeFile(path);
        }
        return bitmap;
    }
}

PhotoBean實體類

package com.example.lenovo.duotupian_demo;

import android.graphics.Bitmap;

public class PhotoBean {
    
    private String path;
    private boolean isSelect;
    private Bitmap bitmap;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public boolean isSelect() {
        return isSelect;
    }

    public void setSelect(boolean select) {
        isSelect = select;
    }

    public Bitmap getBitmap() {
        return bitmap;
    }

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }
}

 

APIService

public interface APIService {

    @POST("UploadDemo4/UploadFile")
    @Multipart
    Call<ResponseBody> postFileUpload(@Part MultipartBody.Part part);
}


當你看到這的時候可能我已經幫到你了,請留下你的腳印,謝謝

轉載必須經過本人同意,謝謝合作