Android客户端上传图片到服务器,服务器存储图片。

来源:互联网 发布:编程算法看不懂 编辑:程序博客网 时间:2024/03/29 16:59

安卓新手,第一次写博客。

http://blog.csdn.net/h7870181/article/details/19971557 主要是学习了这个博文。

自己撸项目时候遇到了 图片上传的问题, 学习 肖赛SoAi 的博文 将问题解决。为了自己记得更熟,写了个上传图片的Demo ,希望能帮助大家。本人还是菜鸟,还请大神指点。

  • 四个步骤
    • 1.获取本地图片或者相机拍照
    • 2.Bitmap转成String (使用Base64)
    • 3.上传图片(使用HttpPost、HttpClient)
    • 4.服务器获取图片,String转成 jpg

获取本地图片或者相机拍照照片

public class MainActivity extends Activity implements OnClickListener {    private Button btn_pick_photo, btn_take_photo,btn_upload_photo,btn_download_photo;    /**     * 用的是 github 开源的智能图片查看器     */    private SmartImageView siv_show_photo;    private ImageView iv_show_photo;    /**     * 相册选取图片     */    private final int CODE_PICK_PHOTO = 0;    /**     * 拍照     */    private final int CODE_TAKE_PHOTO = 1;    private Uri photoUri;    private Bitmap bitmap;    private String photoUrl;    Handler handler = new Handler(){        @Override        public void handleMessage(Message msg) {            // TODO Auto-generated method stub            super.handleMessage(msg);            switch (msg.what) {            case 1:            {                photoUrl = (String) msg.obj;            }                break;            default:                break;            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        initView();        initEvent();    }    private void initView() {        setContentView(R.layout.activity_main);        btn_pick_photo = (Button) findViewById(R.id.btn_pick_photo);        btn_take_photo = (Button) findViewById(R.id.btn_take_photo);        btn_upload_photo = (Button) findViewById(R.id.btn_upload_photo);        btn_download_photo = (Button) findViewById(R.id.btn_download_photo);        siv_show_photo = (SmartImageView) findViewById(R.id.siv_show_photo);        iv_show_photo = (ImageView) findViewById(R.id.iv_show_photo);    }    private void initEvent() {        btn_pick_photo.setOnClickListener(this);        btn_take_photo.setOnClickListener(this);        btn_upload_photo.setOnClickListener(this);        btn_download_photo.setOnClickListener(this);        //将 ic_launcher 转成Bitmap         BitmapDrawable mDrawable =  (BitmapDrawable) iv_show_photo.getDrawable();        bitmap = mDrawable.getBitmap();     }    @Override    public void onClick(View v) {        switch (v.getId()) {        case R.id.btn_pick_photo: {            // 使用 Genymotion模拟器选择图片出错            Intent it = new Intent();            it.setType("image/*");            it.setAction(Intent.ACTION_GET_CONTENT);            startActivityForResult(it, CODE_PICK_PHOTO);        }            break;        case R.id.btn_take_photo: {            // 判断 sd卡是否存在            String storageState = Environment.getExternalStorageState();            if (storageState.equals(Environment.MEDIA_MOUNTED)) {                Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);                ContentValues values = new ContentValues();                photoUri = getContentResolver().insert(                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);                it.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);                startActivityForResult(it, CODE_TAKE_PHOTO);            }        }            break;        case R.id.btn_upload_photo:{            final String imgStr = bitmap2String();            new Thread(new Runnable() {                @Override                public void run() {                    // TODO Auto-generated method stub                    String upLoadResult = new PostUtil().upLoadPhoto(imgStr);                    System.out.println(upLoadResult);                    Message msg = Message.obtain();                    msg.what=1;                    msg.obj = upLoadResult;                    handler.sendMessage(msg);                }            }).start();        }            break;        case R.id.btn_download_photo:{            if(photoUrl!=null){//              System.out.println(photoUrl);                siv_show_photo.setImageUrl(photoUrl);            }        }            break;        default:            break;        }    }    /**     * @return imgStr     */    private String bitmap2String() {        if(bitmap==null){            Toast.makeText(this, "先选取照片", 0).show();            return null;        }        ByteArrayOutputStream stream = new ByteArrayOutputStream();        boolean b = bitmap.compress(CompressFormat.JPEG, 100, stream);        if(b==false){            return null;        }        byte[] bs = stream.toByteArray();        String s = Base64.encodeToString(bs, Base64.DEFAULT);        return s;    }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        if (resultCode == RESULT_OK) {            getPhoto(requestCode, data);        }    }    @SuppressWarnings("deprecation")    @SuppressLint("ShowToast")    private void getPhoto(int requestCode, Intent data) {        //         if (requestCode == CODE_PICK_PHOTO) {            if (data == null) {                Toast.makeText(this, "照片选取出错", 0).show();                return;            }            photoUri = data.getData();            if (photoUri == null) {                Toast.makeText(this, "照片选取出错", 0).show();                return;            }        }        String[] pojo = { MediaStore.Images.Media.DATA };        Cursor cursor = managedQuery(photoUri, pojo, null, null, null);        if (cursor != null) {            int i = cursor.getColumnIndexOrThrow(pojo[0]);            cursor.moveToFirst();            String photoPath = cursor.getString(i);            BitmapFactory.Options options = new BitmapFactory.Options();            options.inSampleSize = 2;            options.inTempStorage = new byte[5 * 1024];             bitmap = BitmapFactory.decodeFile(photoPath, options);//           siv_show_photo.setImageBitmap(bitmap);            iv_show_photo.setImageBitmap(bitmap);        }    }}

通过post上传 imgStr

public class PostUtil {    public static final String url = "http://10.2.141.64:8080/MyImageServer/servlet/MyImageServer";    public PostUtil() {    }    public String upLoadPhoto(String imgStr) {        if(imgStr==null){            System.out.println("imgStr is null");        }        HttpClient httpClient = new DefaultHttpClient();        HttpPost httpPost = new HttpPost(url);        try {            BasicNameValuePair bnvp = new BasicNameValuePair("param", imgStr);            List<BasicNameValuePair>list = new ArrayList<BasicNameValuePair>();            list.add(bnvp);            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "utf-8");            httpPost.setEntity(entity);            HttpResponse response = httpClient.execute(httpPost);            if(response.getStatusLine().getStatusCode()==200){                HttpEntity entity2 = response.getEntity();                String s = EntityUtils.toString(entity2);                return s;            }        } catch (ClientProtocolException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return null;    }}

服务器获取imgStr 并生成jpg文件

public class MyImageServer extends HttpServlet {    private String path;    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doPost(request, response);    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        path = request.getRealPath("/") + "upload/";        request.setCharacterEncoding("utf-8");        response.setCharacterEncoding("utf-8");        PrintWriter out = response.getWriter();        String param = request.getParameter("param");        String imgStr2Image = imgStr2Image(param);        out.print(imgStr2Image);//        out.flush();        out.close();    }    //如果正确, 返回 url 不正确返回 error    private String imgStr2Image(String imgStr) {        // TODO Auto-generated method stub        if(imgStr==null){            return "error:imgStr is null----MyImageServer";        }        File file = new File(path);        if (!file.exists()) {            file.mkdir();        }        Date date = new Date();        long time = date.getTime();        String strName = time+".jpg";        String imgPath = path+strName;        String imgUrl = "http://10.2.141.64:8080/MyImageServer/upload/"+strName;        try {            byte[] bs = new BASE64Decoder().decodeBuffer(imgStr);            for (int i = 0; i < bs.length; i++) {                if (bs[i] < 0) {                    bs[i] += 256;                }            }            OutputStream out = new FileOutputStream(imgPath);            out.write(bs);            out.flush();            out.close();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();            return "error:IOException----MyImageServer";        }        return imgUrl;    }}

谢谢

SmartImageView
http://loopj.com/android-smart-image-view/

Demo
http://download.csdn.net/detail/qq_34653481/9568263


0 0
原创粉丝点击