banner



How To Upload Imae In Android

Upload file/image to the server using volley in Android is a very oftentimes used thing. In well-nigh of the apps, nosotros demand user avatar, i.e. user profile paradigm.

In this article, we are going to see an instance to Android upload a file/image to the server with a Multipart using volley.

What is a MultiPart Asking?

https://source.android.com/reference/tradefed/com/android/tradefed/util/net/HttpMultipartPost

HttpMultipart requests are used to send heavy information or files like audio and video to the server.

Android Volley gives you a very faster and optimized environs to transport heavy data or files to the server. Here I post an image file selected from the gallery.

Using Restful API

Here, I am going to utilise the below API URL to upload the file/image.

ROOT_URL ="http://seoforworld.com/api/v1/file-upload.php"

Please Check PHP code using this URL https://www.maxester.com/weblog/2020/07/28/php-code-for-upload-image-to-server-using-volley-in-android/

Example of upload file/image to a server with the multipart request using volley.

i. Creating an Android project.

  • Open Android Studio and create a new project (I created UploadFile)

2. Add Dependency.

Add Volley to your project. Y'all can rapidly add together it using Gradle. Extract Gradle Scripts and open build.gradle (Module: app)

                              implementation 'com.android.volley:volley:ane.1.1' //Add together this dependency to your projection.            

So your dependencies block volition look like

              dependencies {     implementation fileTree(dir: 'libs', include: ['*.jar'])     implementation 'androidx.appcompat:appcompat:i.1.0'     implementation 'androidx.constraintlayout:constraintlayout:ane.ane.iii'     testImplementation 'junit:junit:4.12'     implementation 'com.android.volley:volley:ane.1.1'     androidTestImplementation 'androidx.test:runner:1.2.0'     androidTestImplementation 'androidx.examination.espresso:espresso-cadre:3.2.0' }            

3. Sync Project.

At present click on Sync Project With Gradle Icon from the top menu and it volition automatically download and add volley library to your project.

iv. Calculation Permission in AndroidMainfest.xml file.

We also need the Internet and Read and Write Storage permission. So withinAndroidManifest.xml add these permissions.

              <uses-permission android:proper noun="android.permission.INTERNET" />     <uses-permission android:proper name="android.permission.READ_EXTERNAL_STORAGE" />     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />            

your AndroidManifest.xml file will look similar as below:-

              <?xml version="1.0" encoding="utf-viii"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.example.uploadfile">     <uses-permission android:name="android.permission.Cyberspace" />     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />       <application         android:allowBackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"         android:roundIcon="@mipmap/ic_launcher_round"         android:supportsRtl="true"         android:usesCleartextTraffic="true"         android:theme="@style/AppTheme">          <action android:name=".MainActivity">             <intent-filter>                 <action android:name="android.intent.action.Master" />                  <category android:proper noun="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>     </application>  </manifest>            

5. User Interface

At present insideactivity_main.xml and write the following XML code into your activity_main.xml.

              <?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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"     tools:context=".MainActivity">      <LinearLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_centerVertical="truthful"         android:orientation="vertical">         <ImageView             android:id="@+id/imageView"             android:layout_width="match_parent"             android:layout_height="200dp" />          <TextView             android:id="@+id/textview"             android:hint="NO Paradigm Slected"             android:layout_gravity="center"             android:gravity="center_horizontal"             android:textStyle="bold"             android:textSize="20sp"             android:layout_width="match_parent"             android:layout_height="wrap_content" />          <Push button             android:id="@+id/buttonUploadImage"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_gravity="center"             android:text="Upload Image" />        </LinearLayout>  </RelativeLayout>                          

six. VolleyMultipartRequest

Here, nosotros demand to perform a multipart asking. But the problem is volley doesn't back up multipart requests directly. So that is why we need to create our Custom Volley Asking.

Create a java class with VolleyMultipartRequest and write the below code in that file.

              // VolleyMultipartRequest.coffee  public class VolleyMultipartRequest extends Request<NetworkResponse> {       private final String twoHyphens = "--";     private final String lineEnd = "\r\n";     private terminal String boundary = "apiclient-" + System.currentTimeMillis();      private Response.Listener<NetworkResponse> mListener;     private Response.ErrorListener mErrorListener;     private Map<String, String> mHeaders;       public VolleyMultipartRequest(int method, String url,                                   Response.Listener<NetworkResponse> listener,                                   Response.ErrorListener errorListener) {         super(method, url, errorListener);         this.mListener = listener;         this.mErrorListener = errorListener;     }      @Override     public Map<String, Cord> getHeaders() throws AuthFailureError {         return (mHeaders != null) ? mHeaders : super.getHeaders();     }      @Override     public Cord getBodyContentType() {         return "multipart/class-data;boundary=" + boundary;     }      @Override     public byte[] getBody() throws AuthFailureError {         ByteArrayOutputStream bos = new ByteArrayOutputStream();         DataOutputStream dos = new DataOutputStream(bos);          try {             // populate text payload             Map<String, String> params = getParams();             if (params != nada && params.size() > 0) {                 textParse(dos, params, getParamsEncoding());             }              // populate data byte payload             Map<String, DataPart> data = getByteData();             if (data != nil && data.size() > 0) {                 dataParse(dos, information);             }              // shut multipart form information after text and file data             dos.writeBytes(twoHyphens + purlieus + twoHyphens + lineEnd);              return bos.toByteArray();         } catch (IOException e) {             e.printStackTrace();         }         render null;     }      /**      * Custom method handle data payload.      *      * @render Map data part label with information byte      * @throws AuthFailureError      */     protected Map<Cord, DataPart> getByteData() throws AuthFailureError {         render null;     }      @Override     protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {         try {             render Response.success(                     response,                     HttpHeaderParser.parseCacheHeaders(response));         } catch (Exception e) {             return Response.error(new ParseError(e));         }     }      @Override     protected void deliverResponse(NetworkResponse response) {         mListener.onResponse(response);     }      @Override     public void deliverError(VolleyError fault) {         mErrorListener.onErrorResponse(fault);     }      /**      * Parse string map into information output stream by key and value.      *      * @param dataOutputStream data output stream handle cord parsing      * @param params           string inputs collection      * @param encoding         encode the inputs, default UTF-8      * @throws IOException      */     individual void textParse(DataOutputStream dataOutputStream, Map<String, String> params, String encoding) throws IOException {         effort {             for (Map.Entry<String, Cord> entry : params.entrySet()) {                 buildTextPart(dataOutputStream, entry.getKey(), entry.getValue());             }         } take hold of (UnsupportedEncodingException uee) {             throw new RuntimeException("Encoding not supported: " + encoding, uee);         }     }      /**      * Parse data into data output stream.      *      * @param dataOutputStream data output stream handle file zipper      * @param information             loop through information      * @throws IOException      */     private void dataParse(DataOutputStream dataOutputStream, Map<String, DataPart> data) throws IOException {         for (Map.Entry<String, DataPart> entry : data.entrySet()) {             buildDataPart(dataOutputStream, entry.getValue(), entry.getKey());         }     }      /**      * Write string data into header and data output stream.      *      * @param dataOutputStream data output stream handle string parsing      * @param parameterName    proper name of input      * @param parameterValue   value of input      * @throws IOException      */     individual void buildTextPart(DataOutputStream dataOutputStream, String parameterName, String parameterValue) throws IOException {         dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);         dataOutputStream.writeBytes("Content-Disposition: grade-data; proper name=\"" + parameterName + "\"" + lineEnd);         dataOutputStream.writeBytes(lineEnd);         dataOutputStream.writeBytes(parameterValue + lineEnd);     }      /**      * Write data file into header and data output stream.      *      * @param dataOutputStream data output stream handle information parsing      * @param dataFile         data byte as DataPart from drove      * @param inputName        name of data input      * @throws IOException      */     private void buildDataPart(DataOutputStream dataOutputStream, DataPart dataFile, Cord inputName) throws IOException {         dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);         dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" +                 inputName + "\"; filename=\"" + dataFile.getFileName() + "\"" + lineEnd);         if (dataFile.getType() != null && !dataFile.getType().trim().isEmpty()) {             dataOutputStream.writeBytes("Content-Type: " + dataFile.getType() + lineEnd);         }         dataOutputStream.writeBytes(lineEnd);          ByteArrayInputStream fileInputStream = new ByteArrayInputStream(dataFile.getContent());         int bytesAvailable = fileInputStream.bachelor();          int maxBufferSize = 1024 * 1024;         int bufferSize = Math.min(bytesAvailable, maxBufferSize);         byte[] buffer = new byte[bufferSize];          int bytesRead = fileInputStream.read(buffer, 0, bufferSize);          while (bytesRead > 0) {             dataOutputStream.write(buffer, 0, bufferSize);             bytesAvailable = fileInputStream.available();             bufferSize = Math.min(bytesAvailable, maxBufferSize);             bytesRead = fileInputStream.read(buffer, 0, bufferSize);         }          dataOutputStream.writeBytes(lineEnd);     }      form DataPart {         private String fileName;         private byte[] content;         individual Cord type;          public DataPart() {         }          DataPart(String proper noun, byte[] data) {             fileName = name;             content = data;         }          String getFileName() {             render fileName;         }          byte[] getContent() {             return content;         }          String getType() {             return type;         }      } }                          

7. Upload file/image to the server.

Now, the principal matter to upload files/images to the server. Nosotros will do it inside the MainActivity.java file.

write the beneath code to your MainActivity.coffee file.

              //MainActivity.java  public class MainActivity extends AppCompatActivity {       private static final String ROOT_URL = "http://seoforworld.com/api/v1/file-upload.php";     private static final int REQUEST_PERMISSIONS = 100;     private static final int PICK_IMAGE_REQUEST =1 ;     private Bitmap bitmap;     private String filePath;     ImageView imageView;     TextView textView;      @Override     protected void onCreate(Parcel savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          //initializing views         imageView =  findViewById(R.id.imageView);         textView =  findViewById(R.id.textview);          //adding click listener to button         findViewById(R.id.buttonUploadImage).setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 if ((ContextCompat.checkSelfPermission(getApplicationContext(),                         Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(),                         Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {                     if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,                             Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,                             Manifest.permission.READ_EXTERNAL_STORAGE))) {                      } else {                         ActivityCompat.requestPermissions(MainActivity.this,                                 new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},                                 REQUEST_PERMISSIONS);                     }                 } else {                     Log.e("Else", "Else");                     showFileChooser();                 }               }         });     }      private void showFileChooser() {         Intent intent = new Intent();         intent.setType("paradigm/*");         intent.setAction(Intent.ACTION_GET_CONTENT);         startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);     }      protected void onActivityResult(int requestCode, int resultCode, Intent data) {         super.onActivityResult(requestCode, resultCode, data);          if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != nada && data.getData() != nada) {             Uri picUri = data.getData();             filePath = getPath(picUri);             if (filePath != nothing) {                 try {                      textView.setText("File Selected");                     Log.d("filePath", String.valueOf(filePath));                     bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), picUri);                     uploadBitmap(bitmap);                     imageView.setImageBitmap(bitmap);                 } catch (IOException due east) {                     e.printStackTrace();                 }             }             else             {                 Toast.makeText(                        MainActivity.this,"no image selected",                                  Toast.LENGTH_LONG).show();             }         }      }     public Cord getPath(Uri uri) {         Cursor cursor = getContentResolver().query(uri, nothing, null, zero, cipher);         cursor.moveToFirst();         Cord document_id = cursor.getString(0);         document_id = document_id.substring(document_id.lastIndexOf(":") + i);         cursor.close();          cursor = getContentResolver().query(                 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,                 null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, nothing);         cursor.moveToFirst();         String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.Data));         cursor.shut();          return path;     }       public byte[] getFileDataFromDrawable(Bitmap bitmap) {         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();         bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);         return byteArrayOutputStream.toByteArray();     }      private void uploadBitmap(final Bitmap bitmap) {          VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Asking.Method.POST, ROOT_URL,                 new Response.Listener<NetworkResponse>() {                     @Override                     public void onResponse(NetworkResponse response) {                         attempt {                             JSONObject obj = new JSONObject(new String(response.data));                             Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();                         } catch (JSONException eastward) {                             e.printStackTrace();                         }                     }                 },                 new Response.ErrorListener() {                     @Override                     public void onErrorResponse(VolleyError mistake) {                         Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();                         Log.e("GotError",""+error.getMessage());                     }                 }) {                         @Override             protected Map<String, DataPart> getByteData() {                 Map<String, DataPart> params = new HashMap<>();                 long imagename = Arrangement.currentTimeMillis();                 params.put("image", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap)));                 return params;             }         };          //adding the request to volley         Volley.newRequestQueue(this).add(volleyMultipartRequest);     }  }                          

eight. Above lawmaking caption.

The beneath code is used to take permission from the device for access gallery on Push button click.

              findViewById(R.id.buttonUploadImage).setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 if ((ContextCompat.checkSelfPermission(getApplicationContext(),                         Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(),                         Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {                     if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,                             Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,                             Manifest.permission.READ_EXTERNAL_STORAGE))) {                      } else {                         ActivityCompat.requestPermissions(MainActivity.this,                                 new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},                                 REQUEST_PERMISSIONS);                     }                 } else {                     Log.e("Else", "Else");                     showFileChooser();                 }               }         });            

In the MainActivity.coffee file, Part showFileChooser() is used to choose an image from the device gallery.

And, To complete the paradigm choosing process we need to override the onActivityResult() method.

getPath() method is used to become the accented path of the file/prototype.

And, uploadBitmap() method is used to upload file/paradigm to the server.

9. Run the Projection

On running the project you will get the following output.

a. Open up the App

www.maxester.com

b. Click on the upload image push button and give permission.

c. Image/File Uploaded

Download Source Code

Please Check PHP code using this URL https://world wide web.maxester.com/weblog/2020/07/28/php-code-for-upload-image-to-server-using-volley-in-android/

Source: https://www.maxester.com/blog/2019/10/04/upload-file-image-to-the-server-using-volley-in-android/

Posted by: houstonallond.blogspot.com

0 Response to "How To Upload Imae In Android"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel