title: Uploading file from Android to laravel via API
body: <p>I'm developing an Application to upload file from Android Application to Laravel Server, Cannot get specific method to upload files. When I test on Postman it works perfectly, but via Android it's not working
  Below I have attached the Laravel Code: </p>
  
  <pre><code> public function uploadFileApp(Request $request){
      $response = array();
      $results = array();
  
      if($request-&gt;hasFile('uploaded_file')){
          $file = $request-&gt;file('uploaded_file');
  
          $file_size = $file-&gt;getSize();
          $file_extension = $file-&gt;getClientOriginalExtension();
  
          $max_id = IndexScan::max('id');
          $tst_id = str_pad($max_id+ 1, 8, '0', STR_PAD_LEFT);
  
          $transaction_id = 'M-'.$tst_id;
          $new_file_name = $transaction_id.".".$file_extension;
  
          $destination_path = public_path('/images/files');
          chmod($destination_path,0777);
          $file-&gt;move($destination_path,$new_file_name);
  
          $FileUpload = new FileUpload;
  
          $FileUpload-&gt;file_name = $new_file_name;
          $FileUpload-&gt;file_size = $file_size;
          $FileUpload-&gt;transaction_id = $transaction_id;
          $FileUpload-&gt;uploaded_by = $request-&gt;input("email");
          $FileUpload-&gt;save();
  
          $get_user_id = User::where(['email' =&gt; $request-&gt;input("email")])-&gt;first();
  
          $IndexScan = new IndexScan;
          $IndexScan-&gt;transaction_id = $transaction_id;
          $IndexScan-&gt;status = 'Scanned';
          $IndexScan-&gt;scanned_by = $get_user_id-&gt;id;
          $IndexScan-&gt;to_be_indexed_by = $get_user_id-&gt;id;
          $IndexScan-&gt;status = 'Scanned';
          $IndexScan-&gt;source = 'Mobile App';
          $IndexScan-&gt;ip_address = request()-&gt;ip();
          $IndexScan-&gt;save();
  
          $response["success"] = 1;
          $response["transaction_id"] = $transaction_id;
  
          $results["results"] = $response;
  
      } else {
          $response["success"] = 0;
          $response["transaction_id"] = "0000000000";
  
          $results["results"] = $response;
      }
      return response()-&gt;json($results);
  }
  </code></pre>
  
  <p>This is the Android Code:</p>
  
  <pre><code> import android.app.Activity;
   import android.app.ProgressDialog;
   import android.content.Context;
   import android.content.Intent;
   import android.content.SharedPreferences;
   import android.graphics.Bitmap;
   import android.net.ConnectivityManager;
   import android.net.NetworkInfo;
   import android.net.Uri;
   import android.os.Bundle;
   import android.os.Environment;
   import android.os.StrictMode;
   import android.provider.MediaStore;
   import android.support.annotation.Nullable;
   import android.support.design.widget.FloatingActionButton;
   import android.support.v4.app.Fragment;
   import android.util.Log;
   import android.view.LayoutInflater;
   import android.view.View;
   import android.view.ViewGroup;
   import android.widget.Toast;
  
   import com.scanlibrary.PickImageFragment;
   import com.scanlibrary.ScanActivity;
   import com.scanlibrary.ScanConstants;
  
   import org.json.JSONException;
   import org.json.JSONObject;
  
   import java.io.BufferedReader;
   import java.io.DataOutputStream;
   import java.io.File;
   import java.io.FileInputStream;
   import java.io.IOException;
   import java.io.InputStreamReader;
   import java.net.HttpURLConnection;
   import java.net.MalformedURLException;
   import java.net.URL;
  
   import static android.content.Context.MODE_PRIVATE;
   import static com.mazelon.invoiceassistant.Constants.Constants.BASE_URL;
   import static com.mazelon.invoiceassistant.Constants.Constants.SharedPrefName;
  
  public class MyInvoices extends Fragment {
  
  FloatingActionButton fab_add;
  private static final int REQUEST_CODE = 99;
  private ProgressDialog pDialog;
  File file;
  String upload_url = BASE_URL+"uploadFileApp";
  String tst_id = "";
  
  public MyInvoices(){}
  
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      View view =  inflater.inflate(R.layout.my_invoices, container, false);
      StrictMode.ThreadPolicy policy = new
              StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
      return view;
  }
  
  @Override
  public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
      super.onViewCreated(view, savedInstanceState);
  
      fab_add = (FloatingActionButton) view.findViewById(R.id.fab_add);
  
      if (!isOnline(getActivity()))
      {
          Toast.makeText(getActivity(), "No network connection", Toast.LENGTH_LONG).show();
          return;
      }
  
      fab_add.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              startScan(ScanConstants.OPEN_CAMERA);
          }
      });
  }
  
  private boolean isOnline(Context mContext) {
      ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo netInfo = cm.getActiveNetworkInfo();
      if (netInfo != null &amp;&amp; netInfo.isConnectedOrConnecting())
      {
          return true;
      }
      return false;
  }
  
  protected void startScan(int preference) {
      Intent intent = new Intent(getContext(), ScanActivity.class);
      intent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, preference);
      startActivityForResult(intent, REQUEST_CODE);
  }
  
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (requestCode == REQUEST_CODE &amp;&amp; resultCode == Activity.RESULT_OK) {
          Uri uri = data.getExtras().getParcelable(ScanConstants.SCANNED_RESULT);
          String file_nm = "";
          Bitmap bitmap = null;
          String email = "";
          try {
              String root = String.valueOf(Environment.getExternalStorageDirectory());
              bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
  
              file_nm = PickImageFragment.file_name;
              SharedPreferences sp = getActivity().getSharedPreferences(SharedPrefName, MODE_PRIVATE);
              email = sp.getString("email","");
          } catch (IOException e) {
              e.printStackTrace();
          }
          uploadFile(upload_url,email,file_nm);
      }
  }
  
  public void uploadFile(final String urlString, String vTitle, String filenm) {
  
  
      URL connectURL = null;
      String Title = null;
      String fileName = null;
      int serverResponseCode = 0;
  
      try{
          connectURL = new URL(urlString);
          Title= vTitle;
          fileName = filenm;
      }catch(Exception ex){
          Log.i("HttpFileUpload","URL Malformatted");
      }
  
      HttpURLConnection conn = null;
      DataOutputStream dos = null;
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary = "*****";
      int bytesRead, bytesAvailable, bufferSize;
      byte[] buffer;
      int maxBufferSize = 1024 * 1024 * 1024;
      File sourceFile = new File(Environment.getExternalStorageDirectory(), "/doc_flux" + "/" + fileName);
  
      if (!sourceFile.isFile()) {
          Log.e("uploadFile", "Source File not exist :" + fileName);
      }
      else {
          try {
  
              Log.e("url", String.valueOf(connectURL));
              Log.e("email", Title);
              Log.e("file_name", fileName);
  
              // open a URL connection to the Servlet
              FileInputStream fileInputStream = new FileInputStream(sourceFile);
  
              // Open a HTTP  connection to  the URL
              conn = (HttpURLConnection) connectURL.openConnection();
              conn.setDoInput(true); // Allow Inputs
              conn.setDoOutput(true); // Allow Outputs
              conn.setUseCaches(false); // Don't use a Cached Copy
              conn.setRequestMethod("POST");
              conn.setRequestProperty("Connection", "Keep-Alive");
              conn.setRequestProperty("ENCTYPE", "multipart/form-data");
              conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
              conn.setRequestProperty("uploaded_file", fileName);
  
              dos = new DataOutputStream(conn.getOutputStream());
  
              dos.writeBytes(twoHyphens + boundary + lineEnd);
              dos.writeBytes("Content-Disposition: form-data; name=\"email\"" + lineEnd);
              dos.writeBytes(lineEnd);
              dos.writeBytes(Title);
              dos.writeBytes(lineEnd);
              dos.writeBytes(twoHyphens + boundary + lineEnd);
  
              dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd);
              dos.writeBytes(lineEnd);
  
              // create a buffer of  maximum size
              bytesAvailable = fileInputStream.available();
  
              bufferSize = Math.min(bytesAvailable, maxBufferSize);
              buffer = new byte[bufferSize];
  
              // read file and write it into form...
              bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  
              while (bytesRead &gt; 0) {
  
                  dos.write(buffer, 0, bufferSize);
                  bytesAvailable = fileInputStream.available();
                  bufferSize = Math.min(bytesAvailable, maxBufferSize);
                  bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  
              }
  
              // send multipart form data necesssary after file data...
              dos.writeBytes(lineEnd);
              dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
  
              // Responses from the server (code and message)
              serverResponseCode = conn.getResponseCode();
              String serverResponseMessage = conn.getResponseMessage();
  
              Log.i("uploadFile", "HTTP Response is : "
                      + serverResponseMessage + ": " + serverResponseCode);
  
              if (serverResponseCode == 200) {
  
                  final HttpURLConnection finalConn = conn;
                  getActivity().runOnUiThread(new Runnable() {
                      public void run() {
                          BufferedReader in = null;
                          StringBuffer response = null;
                          try {
                              in = new BufferedReader(
                                      new InputStreamReader(finalConn.getInputStream()));
                              String inputLine;
                              response = new StringBuffer();
                              while ((inputLine = in.readLine()) != null) {
                                  response.append(inputLine);
                              }
  
                              in.close();
                              Log.e("jsonreply",response.toString());
                          } catch (IOException e) {
                              e.printStackTrace();
                          }
  
                          try {
                              JSONObject mainObject = new JSONObject(response.toString());
                              JSONObject uniObject = mainObject.getJSONObject("results");
                              tst_id = uniObject.getString("transaction_id");
                          } catch (JSONException e) {
                              e.printStackTrace();
                          }
                          String msg = "File Upload Completed.";
  
                          Toast.makeText(getActivity(), msg,
                                  Toast.LENGTH_SHORT).show();
                      }
                  });
                  Intent intent = new Intent(getActivity(), UploadSuccess.class);
                  intent.putExtra("transaction_id",tst_id);
                  startActivity(intent);
              }
  
              //close the streams //
              fileInputStream.close();
              dos.flush();
              dos.close();
  
          } catch (MalformedURLException ex) {
              if(pDialog!=null) {
                  pDialog.dismiss();
              }
              ex.printStackTrace();
  
              getActivity().runOnUiThread(new Runnable() {
                  public void run() {
                      Toast.makeText(getActivity(), "MalformedURLException",
                              Toast.LENGTH_SHORT).show();
                  }
              });
  
              Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
          } catch (Exception e) {
              if(pDialog!=null) {
                  pDialog.dismiss();
              }
              e.printStackTrace();
  
              getActivity().runOnUiThread(new Runnable() {
                  public void run() {
                      Toast.makeText(getActivity(), "Got Exception : see logcat ",
                              Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e("Upload server Exception", "Exception : "
                      + e.getMessage(), e);
          }
          if(pDialog!=null) {
              pDialog.dismiss();
          }
  
      }
  }
  }
  </code></pre>
  
  <p>And When I use the access the above Laravel API service from postman my image is getting uploaded(I mean it's getting through the if($request->hasFile('uploaded_file')),but when I try through the above android code, It's not working(I mean it's getting to the else statement).</p>