简单的图片上传和下载

一.图片的上传

1.图片的来源无非是照相和图库的选择 将选择的图片进行封装到bean类中进行返回,之后通过上传的方式去上传

2.上传的方式也是两种方式,通过的字符串或者流的方式(先建立链接在通过流)

3.服务器返回的数据是上传成功与否的标识

4.使用框架进行上传。如:okhttp,xUtils,volley等等;

二.图片的下载

1.三级缓存()

2.第三方框架

更多的了解:http://blog.sina.com.cn/s/blog_9ac333de0101gptn.html
      http://blog.csdn.net/u011240877/article/details/45824855

补充:

图片上传的方法:

直接从项目中copy的,可以参考这块的思路

在gridView上进行展示上传的个数

    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater; // 视图容器
        private int selectedPosition = -1;// 选中的位置
        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        // 从新加载并且上传新的多余的图片
        public void update1() {
            loading1();
        }
        public int getCount() {
            return (Bimp.bmp.size() + 1);
        }

        public Object getItem(int arg0) {

            return null;
        }

        public long getItemId(int arg0) {

            return arg0;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        /**
         * ListView Item设置
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            // final int coord = position;
            ViewHolder holder = null;

            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_published_grida,
                        parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                holder.customView = (CustomView6) convertView
                        .findViewById(R.id.customView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            // customViewList.get(0).setVisibility(View.GONE);
            holder.image.setVisibility(View.VISIBLE);
            holder.customView.setProgress(0);
            holder.customView.setVisibility(CustomView6.VISIBLE);

            if (position == Bimp.bmp.size()) {

                holder.image.setImageBitmap(BitmapFactory.decodeResource(
                        getResources(), R.drawable.icon_addpic_unfocused));
                holder.customView.setVisibility(CustomView6.GONE);

            } else {
                holder.image.setImageBitmap(Bimp.bmp.get(position));
            }

            // 是否存在key(适用于拍照)
            // 只要有选择照片的就会进来(包括第一次是选择照片)
            if(Bimp.drr != null && Bimp.drr.size() > position){
                if (Bimp.listtag != null && Bimp.listtag.size() > position) {
                // 有上传成功的照片时会走
                if (pictureTypeMap.containsKey(Bimp.drr.get(position).uuid)) {
                    
                    if ("T".equals(pictureTypeMap.get(Bimp.drr.get(position).uuid))){
                        //角标越界
                        if (Bimp.listtag.size() > position) {
                            
                            if (Bimp.listtag.get(position).equals(Bimp.drr.get(position).uuid)) {
                                
                                holder.customView.setProgress(100);
                            
                            }
                        }
                    }
                }
            }

                
            }
            if (position >= 9) {
                holder.image.setVisibility(View.GONE);
                cameraBtn.setVisibility(View.GONE);
                if (Selected == 9) {
                    Toast.makeText(FieldInspecRegisterActivity.this,
                            "单次最大上传图片为9张", 0).show();
                }

            }

            return convertView;
        }
    }
    public class ViewHolder {
        public ImageView image;
        public CustomView6 customView;
    }
    //根据返回的集合的内容来展示图片
    private void loading1() {
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    if (Bimp.max == Bimp.drr.size()) {
                        Message message = new Message();
                        message.what = CHANGDATA;
                        handler.sendMessage(message);
                        break;
                    } else {
                        try {
                            String path = Bimp.drr.get(Bimp.max).path;
                            Bitmap bm = Bimp.revitionImageSize(path);
                            Bimp.bmp.add(bm);
                            String newStr = path.substring(
                                    path.lastIndexOf("/") + 1,
                                    path.lastIndexOf("."));
                            FileUtils.saveBitmap(bm, "" + newStr);
                            Bimp.max += 1;
                            Message message = new Message();
                            message.what = CHANGDATA;
                            handler.sendMessage(message);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }
    //监听物理返回键
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            
            if (Bimp.drr.size() > 0 && Selected < Bimp.drr.size()) {
                //整在上传时进行对话框判断是否终止
                showMyDialog();
            } else {
                if (attendance.getType().equals("back")) {
                    finish();
                } else {
                    if (!(Bimp.drr.size() > Selected)) {
                        //上传的完成时
                        uploadPicStr();
                    }
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    //当界面返回时调用改方法,adapter适配
    protected void onRestart() {
        adapter2.update1();
        super.onRestart();
    }
    // 界面销毁时,有数据需要清除
    protected void onDestory() {
        //广播注销
        unregisterBroadcastReceiver();
        
        if (Bimp.drr.size() > 0) {
            Bimp.drr.clear();
        }
        if (Bimp.listtag.size() > 0) {
            Bimp.listtag.clear();
        }
        if (Bimp.bmp.size() > 0) {
            Bimp.bmp.clear();
        }

        FileUtils.deleteDir();
        Bimp.max = 0;
        Bimp.act_bool = false;

        }
    //
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 拍照
        if (resultCode == RESULT_OK && (requestCode == PHOTO_GRAPH )) {
            
            PhotoSelect++;
            //拿到路径再次请求上传
            if (picture.getAbsolutePath().length() > 0) {
                //每次拿到给定图片的对象
                UUID randomUUID = UUID.randomUUID();
                BeanPicUpload mbeanPicUpload = new BeanPicUpload();
                mbeanPicUpload.path=picture.getAbsolutePath();
                mbeanPicUpload.uuid = randomUUID+"";
                mbeanPicUpload.isSussecs=true;
                Bimp.drr.add(mbeanPicUpload);
                
            }    
        }
    }
    /**
     * 上传图片
     * 在生命止周期的方法去做
     * 每次返回到当前的界面时就会执行上传的方法
     * 这个方法在子线程中去完成,只要这个所有图片的 只有未成功上传的图片,该方法就在一直执行,直到到上传完成;
     * */
        @Override
        protected void onResume() {
            super.onResume();
            if (isNetworkAvailable(FieldInspecRegisterActivity.this)) {
                if(Bimp.drr.size()>0){
                    //每次进界面时都会重新调用
                    uploadThreadTest(Bimp.drr);
                    L.e(TAG, "wode 每次必须执行的方法  且这里面现在没有要执行的方法: "+Bimp.drr.toString());
                    
                }
            } else {
                Toast.makeText(FieldInspecRegisterActivity.this, "请检查网络",
                        Toast.LENGTH_SHORT).show();
            }
        }
    /**
     * 上传图片的方法
     * @param mBeandrr
     */
    private void uploadThreadTest(final List<BeanPicUpload> mListBeandrr) {
        
        new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < mListBeandrr.size(); i++) {
                    
                    if(!Bimp.listtag.contains(mListBeandrr.get(i).uuid)){
                        
                        
                        upload(mListBeandrr.get(i));
                        
                        L.e(TAG, "Bimp.listtag集合中的元素 "+Bimp.listtag.toString());
                        L.e(TAG, "要上传的数据"+mListBeandrr.get(i));
                    }
                    
                }
                
                
            }

        }).start();
    }
    private boolean isnextone =false ;
    /**
     * 在子线程中操作集合
     */
    private void upload(BeanPicUpload beanPicUpload) {
        
        //传递过来drr
        String url_ = "http://cserverupload.cserver.cn/fileupload.do";
        int res = -1;
        String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
        String PREFIX = "--";
        String LINE_END = " ";
        String CONTENT_TYPE = "multipart/form-data"; // 内容类型
        
        if (isNetworkAvailable(FieldInspecRegisterActivity.this)) {
           if(Bimp.drr.size()>0){
             //图片上传  已上传的就不要在上传(且开始时上传的集合是空)  
                   //ture表示要上传的
                   L.e(TAG,"shenme    时候去执行了            :"+Bimp.listtag.size());

                   uploadPic(url_, BOUNDARY, PREFIX, LINE_END, CONTENT_TYPE,beanPicUpload);

           }   
        } else {
            Toast.makeText(FieldInspecRegisterActivity.this, "请检查网络", 0).show();
        }
        }
        


    private void uploadPic(String url_, String BOUNDARY, String PREFIX,
            String LINE_END, String CONTENT_TYPE,BeanPicUpload picbean) {
        
            if(!isnextone){
                isnextone=true;    
            Log.e(TAG, "传进来的数据   开始上传的数据 "+picbean.toString());
                if((!picbean.path.equals(""))&&picbean.path!=null){
                    
                    File perfile = new File(picbean.path);
                    
                    int res = -1;
                    // 图片上传
                    if (perfile != null) {
                        HttpURLConnection conn;
                        URL url;
                        try {
                            url = new URL(url_);
                            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);

                            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                            L.e(TAG, "wode 数据输出流建立");
                            /**
                             * 当文件不为空时执行上传
                             * name里面的值为服务器端需要key
                             * 只有这个key 才可以得到对应的文件filename是文件的名字,包含后缀名
                             *
                             */
                            StringBuffer sb = new StringBuffer();
                            sb.append(PREFIX);
                            sb.append(BOUNDARY);
                            sb.append(LINE_END);
                            
                            L.e(TAG, "wode shangchuan de wenjian 名称:"+perfile.getName());
                            
                            sb.append("Content-Disposition: form-data; name="file"; filename=""+ perfile.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(perfile);
                            long total = perfile.length();
                            byte[] bytes = new byte[1024 * 10];
                            int len = 0;
                            int count = 0;
                            int progress = 0;
                            while ((len = is.read(bytes)) != -1) {
                                count += len;
                                progress = ((int) ((count / (float) total) * 100));
                                if (progress == 100) {

                                }
                                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=成功 当响应成功,获取响应的流
                             */
                            res = conn.getResponseCode();
                            if (res == 200) {
                                InputStream input = conn.getInputStream();
                                StringBuffer sb1 = new StringBuffer();
                                int ss;
                                while ((ss = input.read()) != -1) {
                                    sb1.append((char) ss);
                                }
                                String result = sb1.toString();
                                JSONObject jsonObject;
                                jsonObject = new JSONObject(result);
                                uploadStr.append(jsonObject.optString("downloadUrl"));
                                uploadStr.append(",");
                                uploadNewStr.append(jsonObject.optString("newdownloadUrl"));
                                uploadNewStr.append(",");
                                
                                //上传成功时进行保存
                                Selected++;// 成功的第几张图片
                                if (!pictureTypeMap.containsKey(picbean.uuid)) {
                                    // 为什么在这打不到phototselect的值
                                    pictureTypeMap.put(picbean.uuid, "T");// 选择的
                                    
                                    L.e(TAG, "集合中保存了数据   :"+picbean.uuid+""+"   "+"T");
                                }
                                // 使用bean类来记录所有的图片
                                
                                Bimp.listtag.add(picbean.uuid);
                                // 这个发送消息的时候是关键
                                handler.sendEmptyMessage(UPLOADSUCCESS);
                                
                                isnextone = false;
                                Log.e(TAG, "上传成功就会发送消息 Bimp.listtag 集合"+Bimp.listtag.toString());
                                Log.e(TAG, "上传成功就会发送消息 Bimp.drr  集合 "+Bimp.drr.toString());
                            } else if (res == 404) {
                                Toast.makeText(FieldInspecRegisterActivity.this, "网页找不到", 0)
                                        .show();
                            } else if (res == 500) {
                                Toast.makeText(FieldInspecRegisterActivity.this, "服务器有问题",
                                        0).show();
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "异常  " + e.toString());
                            e.printStackTrace();
                        }
                    }
                }    
            }    
        }           

原文地址:https://www.cnblogs.com/zyanrong/p/5486413.html