Android使用Volley将图像上传到服务器

Here you will learn about android upload image to server using volley library.

在这里,您将了解有关使用凌空库将android上传图像到服务器的信息。

At server side I have used java web service and for sending image to server volley library is used.

在服务器端,我使用了Java Web服务,并使用了将图像发送到服务器凌空库的方法。

How it works?

这个怎么运作?

  • The user chooses an image from gallery and click on upload button.

    用户从图库中选择图像,然后单击上载按钮。

  • The image is then converted into Base64 string format and sent to server using volley network library.

    然后将图像转换为Base64字符串格式,并使用凌空网络库将其发送到服务器。

  • Now at server side this Bas64 string is converted back into image and stored at some location.

    现在,在服务器端,此Bas64字符串将转换回映像并存储在某个位置。

Android使用Volley将图像上传到服务器 (Android Upload Image to Server Using Volley)

服务器代码 (Server Code)

Below is the code for server. It is a java web service. If you don’t know how to make web service in java then read below tutorial.

下面是服务器的代码。 这是一个Java Web服务 。 如果您不知道如何使用Java进行Web服务,请阅读以下教程。

Also Read: Create Simple Java RESTful Web Services Using Jersey

另请阅读: 使用Jersey创建简单的Java RESTful Web服务

DemoService.java

DemoService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package example;
import java.io.FileOutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.commons.codec.binary.Base64;
@Path("/DemoService")
public class DemoService {
@POST
@Path("/upload")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public String uploadImage(@FormParam("image") String image) {
String result="false";
//decode Base64 String to image
try{
FileOutputStream fos = new FileOutputStream("H:/image.jpg"); //change the path where you want to save the image
byte byteArray[] = Base64.decodeBase64(image);
fos.write(byteArray);
result="true";
fos.close();
}
catch(Exception e){
e.printStackTrace();
}
return result;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package example ;
import java . io . FileOutputStream ;
import javax . ws . rs . Consumes ;
import javax . ws . rs . FormParam ;
import javax . ws . rs . POST ;
import javax . ws . rs . Path ;
import javax . ws . rs . Produces ;
import javax . ws . rs . core . MediaType ;
import org . apache . commons . codec . binary . Base64 ;
@Path ( "/DemoService" )
public class DemoService {
@POST
@Path ( "/upload" )
@Consumes ( MediaType . APPLICATION_FORM_URLENCODED )
@Produces ( MediaType . TEXT_HTML )
public String uploadImage ( @FormParam ( "image" ) String image ) {
String result = "false" ;
//decode Base64 String to image
try {
FileOutputStream fos = new FileOutputStream ( "H:/image.jpg" ) ; //change the path where you want to save the image
byte byteArray [ ] = Base64 . decodeBase64 ( image ) ;
fos . write ( byteArray ) ;
result = "true" ;
fos . close ( ) ;
}
catch ( Exception e ) {
e . printStackTrace ( ) ;
}
return result ;
}
}

Android专案 (Android Project)

1. Now create a new android project with package name com.androiduploadimage

1.现在,使用包名称com.androiduploadimage创建一个新的android项目。

2. Add dependency for volley library by adding following line in build.gradle file.

2.通过在build.gradle文件中添加以下行来添加凌空库的依赖关系。

1
compile 'com.android.volley:volley:1.0.0'
1
compile 'com.android.volley:volley:1.0.0'

3. Add internet access permission in AndroidManifest.xml file.

3.在AndroidManifest.xml文件中添加Internet访问权限。

4. Add following code in respective files.

4.在相应文件中添加以下代码。

activity_main.xml

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="15dp"
    android:paddingLeft="15dp"
    android:paddingRight="15dp"
    android:paddingTop="15dp"
    tools:context="com.androiduploadimage.MainActivity"
    android:orientation="vertical">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:id="@+id/image"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Choose"
        android:id="@+id/choose"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Upload"
        android:id="@+id/upload"/>
</LinearLayout>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<? xml version = "1.0" encoding = "utf-8" ?>
<LinearLayout xmlns : android = "http://schemas.android.com/apk/res/android"
    xmlns : tools = "http://schemas.android.com/tools"
    android : layout_width = "match_parent"
    android : layout_height = "match_parent"
    android : paddingBottom = "15dp"
    android : paddingLeft = "15dp"
    android : paddingRight = "15dp"
    android : paddingTop = "15dp"
    tools : context = "com.androiduploadimage.MainActivity"
    android : orientation = "vertical" >
     <ImageView
        android : layout_width = "match_parent"
        android : layout_height = "200dp"
        android : id = "@+id/image" />
     <Button
        android : layout_width = "match_parent"
        android : layout_height = "wrap_content"
        android : text = "Choose"
        android : id = "@+id/choose" />
     <Button
        android : layout_width = "match_parent"
        android : layout_height = "wrap_content"
        android : text = "Upload"
        android : id = "@+id/upload" />
</LinearLayout>

MainActivity.java

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package com.androiduploadimage;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
    ImageView image;
    Button choose, upload;
    int PICK_IMAGE_REQUEST = 111;
    String URL ="http://192.168.1.101/JavaRESTfullWS/DemoService/upload";
    Bitmap bitmap;
    ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = (ImageView)findViewById(R.id.image);
        choose = (Button)findViewById(R.id.choose);
        upload = (Button)findViewById(R.id.upload);
        //opening image chooser option
        choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_PICK);
                startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
            }
        });
        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage("Uploading, please wait...");
                progressDialog.show();
                //converting image to base64 string
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] imageBytes = baos.toByteArray();
                final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
                //sending image to server
                StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>(){
                    @Override
                    public void onResponse(String s) {
                        progressDialog.dismiss();
                        if(s.equals("true")){
                            Toast.makeText(MainActivity.this, "Uploaded Successful", Toast.LENGTH_LONG).show();
                        }
                        else{
                            Toast.makeText(MainActivity.this, "Some error occurred!", Toast.LENGTH_LONG).show();
                        }
                    }
                },new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Toast.makeText(MainActivity.this, "Some error occurred -> "+volleyError, Toast.LENGTH_LONG).show();;
                    }
                }) {
                    //adding parameters to send
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> parameters = new HashMap<String, String>();
                        parameters.put("image", imageString);
                        return parameters;
                    }
                };
                RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
                rQueue.add(request);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            try {
                //getting image from gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //Setting image to ImageView
                image.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package com . androiduploadimage ;
import android . app . ProgressDialog ;
import android . content . Intent ;
import android . graphics . Bitmap ;
import android . net . Uri ;
import android . provider . MediaStore ;
import android . support . v7 . app . AppCompatActivity ;
import android . os . Bundle ;
import android . util . Base64 ;
import android . view . View ;
import android . widget . Button ;
import android . widget . ImageView ;
import android . widget . Toast ;
import com . android . volley . AuthFailureError ;
import com . android . volley . Request ;
import com . android . volley . RequestQueue ;
import com . android . volley . Response ;
import com . android . volley . VolleyError ;
import com . android . volley . toolbox . StringRequest ;
import com . android . volley . toolbox . Volley ;
import java . io . ByteArrayOutputStream ;
import java . util . HashMap ;
import java . util . Map ;
public class MainActivity extends AppCompatActivity {
     ImageView image ;
     Button choose , upload ;
     int PICK_IMAGE_REQUEST = 111 ;
     String URL = "http://192.168.1.101/JavaRESTfullWS/DemoService/upload" ;
     Bitmap bitmap ;
     ProgressDialog progressDialog ;
     @Override
     protected void onCreate ( Bundle savedInstanceState ) {
         super . onCreate ( savedInstanceState ) ;
         setContentView ( R . layout . activity_main ) ;
         image = ( ImageView ) findViewById ( R . id . image ) ;
         choose = ( Button ) findViewById ( R . id . choose ) ;
         upload = ( Button ) findViewById ( R . id . upload ) ;
         //opening image chooser option
         choose . setOnClickListener ( new View . OnClickListener ( ) {
             @Override
             public void onClick ( View v ) {
                 Intent intent = new Intent ( ) ;
                 intent . setType ( "image/*" ) ;
                 intent . setAction ( Intent . ACTION_PICK ) ;
                 startActivityForResult ( Intent . createChooser ( intent , "Select Image" ) , PICK_IMAGE_REQUEST ) ;
             }
         } ) ;
         upload . setOnClickListener ( new View . OnClickListener ( ) {
             @Override
             public void onClick ( View v ) {
                 progressDialog = new ProgressDialog ( MainActivity . this ) ;
                 progressDialog . setMessage ( "Uploading, please wait..." ) ;
                 progressDialog . show ( ) ;
                 //converting image to base64 string
                 ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ;
                 bitmap . compress ( Bitmap . CompressFormat . JPEG , 100 , baos ) ;
                 byte [ ] imageBytes = baos . toByteArray ( ) ;
                 final String imageString = Base64 . encodeToString ( imageBytes , Base64 . DEFAULT ) ;
                 //sending image to server
                 StringRequest request = new StringRequest ( Request . Method . POST , URL , new Response . Listener <String> ( ) {
                     @Override
                     public void onResponse ( String s ) {
                         progressDialog . dismiss ( ) ;
                         if ( s . equals ( "true" ) ) {
                             Toast . makeText ( MainActivity . this , "Uploaded Successful" , Toast . LENGTH_LONG ) . show ( ) ;
                         }
                         else {
                             Toast . makeText ( MainActivity . this , "Some error occurred!" , Toast . LENGTH_LONG ) . show ( ) ;
                         }
                     }
                 } , new Response . ErrorListener ( ) {
                     @Override
                     public void onErrorResponse ( VolleyError volleyError ) {
                         Toast . makeText ( MainActivity . this , "Some error occurred -> " + volleyError , Toast . LENGTH_LONG ) . show ( ) ; ;
                     }
                 } ) {
                     //adding parameters to send
                     @Override
                     protected Map < String , String > getParams ( ) throws AuthFailureError {
                         Map < String , String > parameters = new HashMap < String , String > ( ) ;
                         parameters . put ( "image" , imageString ) ;
                         return parameters ;
                     }
                 } ;
                 RequestQueue rQueue = Volley . newRequestQueue ( MainActivity . this ) ;
                 rQueue . add ( request ) ;
             }
         } ) ;
     }
     @Override
     protected void onActivityResult ( int requestCode , int resultCode , Intent data ) {
         super . onActivityResult ( requestCode , resultCode , data ) ;
         if ( requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data . getData ( ) != null ) {
             Uri filePath = data . getData ( ) ;
             try {
                 //getting image from gallery
                 bitmap = MediaStore . Images . Media . getBitmap ( getContentResolver ( ) , filePath ) ;
                 //Setting image to ImageView
                 image . setImageBitmap ( bitmap ) ;
             } catch ( Exception e ) {
                 e . printStackTrace ( ) ;
             }
         }
     }
}

Screenshot

屏幕截图

Android Upload Image to Server Using Volley

You can ask your queries in comment section.

您可以在评论部分提问。

翻译自: https://www.thecrazyprogrammer.com/2016/09/android-upload-image-server-using-volley.html