Android :okhttp+Springmvc文件解析器實現android向服務器上傳照片

A.前言:爲了解決安卓端向服務器上傳照片的問題

  1.得到相冊權限,選取照片,取到照片的urlandroid

  2.使用okhttp訪問服務器並向服務器傳照片web

  3.配置springmvc文件解析器spring

  4.搭建服務器,獲取數據保存照片json

 B.Android添加一個按鈕和一個ImageView,設置它的點擊事件,打開相冊選擇照片,解析獲得照片的本機url,並把照片顯示到ImageView裏

    添加權限:服務器

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />

    導包:網絡

compile 'com.squareup.okhttp3:okhttp:3.4.1'

     按鈕事件:打開相冊選取照片    調用startActivityForResult();mvc

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=(Button)findViewById(R.id.button   );w
        image=(ImageView) findViewById(R.id.image);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, 100);
            }
        });
    }

 

     重寫onActivityResult()方法  解析照片得到url 覆給全局變量,並把照片顯示到imageView。調用自定義的uploadImage(),向服務器發送數據app

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 100:
                switch (resultCode) {
                    case RESULT_OK:
                        Uri uri = data.getData();
                       img_src = uri.getPath();//這是本機的圖片路徑
                        ContentResolver cr = this.getContentResolver();
                        try {
                            Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                        /* 將Bitmap設定到ImageView */
                            image.setImageBitmap(bitmap);
                            String[] proj = {MediaStore.Images.Media.DATA};
                            CursorLoader loader = new CursorLoader(this, uri, proj, null, null, null);
                            Cursor cursor = loader.loadInBackground();
                            if (cursor != null) {
                                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                                cursor.moveToFirst();
                                img_src = cursor.getString(column_index);//圖片實際路徑
                            }

                            cursor.close();
                            this.uploadImage();
                        } catch (FileNotFoundException e) {
                            Log.e("cwd", e.getMessage(), e);
                        }

                        break;
                }
                break;

        }
    }

 

      實現uploadImage(),使用okhttp向服務器傳數據dom

 public void uploadImage() {
         Log.d("cwd","uploadImage");
        new  Thread(new Runnable() {
            @Override
            public void run() {
                File file=new File(img_src);
                RequestBody requestBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                    .addFormDataPart("jsonfile", file.getName(),
                            RequestBody.create(MediaType.parse("multipart/form-data"), file))//文件
                        .build();
                  Request request = new Request.Builder()
                      .url("http://3i157k1732.qicp.vip/springmvc03/jsonsrc").post(requestBody)
                          .build();
                OkHttpClient client=new OkHttpClient();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d("cwd", "上傳失敗"+e.getLocalizedMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.d("cwd","上傳成功"+response.body().string());
                    }
                });
            }
        }).start();

    }

C.服務器端,配置springmvc文件解析器,定義照片數據處理的方法

    idea導包:ide

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.0</version>
</dependency>

    在Springmvc的配置文件中配置文件解析器:注意   bean 的id必須爲multipartResolver

 

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760"/>

    </bean>

 

 

     定義處理方法:  必須使用RequestParam來綁定參數,值爲okhttp上傳數據的key值

        注意!!!

 

 

@RequestMapping(value = "/jsonsrc")
    public String jsonsrc(HttpServletRequest request,@RequestParam("jsonfile") MultipartFile jsonfile) throws IOException {
        System.out.println("jsonsrc");
        String path=request.getSession().getServletContext().getRealPath("/uploads/");
        File file=new File(path);
        if(!file.exists()){
            file.mkdir();
        }
        String filename=jsonfile.getOriginalFilename();
        String uuid= UUID.randomUUID().toString().replace("-","");
        filename=uuid+filename;
        jsonfile.transferTo(new File(path,filename));
        return "succes";
    }

 

 

 這樣就完成了!!!

okhttp用來訪問網絡,能夠拿數據,也能夠向服務器傳數據!

使用springmvc文件解析器,讓咱們不用去注重解析文件,只須要保存文件!

相關文章
相關標籤/搜索