title: Android Upload File to server giving a 'Source File Does not exist' error
body: <p>I am coding an activity to upload any types of files to a server.</p>
  
  <p>It retrieves the file name just fine and assigns it to a TextView; but, when I select my upload button it quickly gives me a "Source File Does not exist' error and does not upload the file to my server. (The PHP code is working fine, as I have used it in other places)</p>
  
  <p>I believe the issue is with the uploadFilePath variable in the OnActivityResult. I'm not sure why. Any help is appreciated. Thanks.</p>
  
  <p>Upload call:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>private void uploadFile(final String media_id) {
          class UploadFile extends AsyncTask&lt;Void, Void, String&gt; {
  
              ProgressDialog uploading;
  
              @Override
              protected void onPreExecute() {
                  super.onPreExecute();
                  uploading = ProgressDialog.show(FileUpload.this, "Uploading File", "Please wait...", false, false);
              }
  
              @Override
              protected void onPostExecute(String s) {
                  super.onPostExecute(s);
                  uploading.dismiss();
                  finish();
                  Toast.makeText(getApplicationContext(), "File uploaded successfully.", Toast.LENGTH_LONG).show();
              }
  
              @Override
              protected String doInBackground(Void... params) {
                  String filepath = uploadFilePath;
                  String msg = uploadFile(filepath, media_id);
                  return msg;
              }
          }
          UploadFile uv = new UploadFile();
          uv.execute();
      }</code></pre>
  </div>
  </div>
  </p>
  
  <p>Upload Code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>public String uploadFile(String file, final String id) {
  
          String fileName = file;
          HttpURLConnection conn = null;
          DataOutputStream dos = null;
          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary = "*****";
          int bytesRead, bytesAvailable, bufferSize;
          byte[] buffer;
          int maxBufferSize = 1 * 1024 * 1024;
  
          File sourceFile = new File(file);
          if (!sourceFile.isFile()) {
              Log.e("Error", "Source File Does not exist");
              return null;
          }
  
          try {
              FileInputStream fileInputStream = new FileInputStream(sourceFile);
              URL url = new URL(UPLOAD_URL);
              conn = (HttpURLConnection) url.openConnection();
              conn.setDoInput(true);
              conn.setDoOutput(true);
              conn.setUseCaches(false);
              conn.setRequestMethod("POST");
              conn.setRequestProperty("Connection", "Keep-Alive");
              conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
              conn.setRequestProperty("myFile", fileName);
  
              dos = new DataOutputStream(conn.getOutputStream());
  
              dos.writeBytes(twoHyphens + boundary + lineEnd);
  
              //Adding Parameter name
  
              dos.writeBytes("Content-Disposition: form-data; name=\"media_id\"" + lineEnd);
              dos.writeBytes(lineEnd);
              dos.writeBytes(media_id); // mobile_no is String variable
              dos.writeBytes(lineEnd);
  
              //Adding Parameter filepath
  
              dos.writeBytes(twoHyphens + boundary + lineEnd);
              String filepath="url"+fileName;
  
              dos.writeBytes("Content-Disposition: form-data; name=\"filepath\"" + lineEnd);
              dos.writeBytes(lineEnd);
              dos.writeBytes(filepath); // mobile_no is String vaiable
              dos.writeBytes(lineEnd);
  
              //Adding Media File Parameter
              dos.writeBytes(twoHyphens + boundary + lineEnd);
              dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + fileName + "\"" + lineEnd);
              dos.writeBytes(lineEnd);
              bytesAvailable = fileInputStream.available();
              Log.i("Result", "Initial .available : " + bytesAvailable);
              bufferSize = Math.min(bytesAvailable, maxBufferSize);
              buffer = new byte[bufferSize];
              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);
              }
  
              dos.writeBytes(lineEnd);
              dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
  
              serverResponseCode = conn.getResponseCode();
  
              fileInputStream.close();
              dos.flush();
              dos.close();
          } catch (MalformedURLException ex) {
              ex.printStackTrace();
          } catch (Exception e) {
              e.printStackTrace();
          }
  
          if (serverResponseCode == 200) {
              StringBuilder sb = new StringBuilder();
              try {
                  BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                  String line;
                  while ((line = rd.readLine()) != null) {
                      sb.append(line);
                  }
                  rd.close();
              } catch (IOException ioex) {
              }
              return sb.toString();
          }else {
              return "Could not upload";
          }
      }</code></pre>
  </div>
  </div>
  </p>
  
  <p>OnActivityResult code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code> @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
          // When an Image is picked
          if (requestCode == REQUEST_CODE_DOC) {
              if (resultCode == RESULT_OK) {
                  // Get the Image from data
                  Uri selectedFilePath = data.getData();
  
                  String uriString = selectedFilePath.toString();
                  File fileToUpload = new File(uriString);
                  uploadFilePath = fileToUpload.getAbsolutePath();
  
                  if (uriString.startsWith("content://")) {
                      Cursor cursor = null;
                      try {
                          cursor = getContentResolver().query(selectedFilePath, null, null, null, null);
                          if (cursor != null &amp;&amp; cursor.moveToFirst()) {
                              uploadFileName =         cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                              filename.setText(uploadFileName);
                              uploadFile.setVisibility(View.VISIBLE);
                              mEditText.setVisibility(View.VISIBLE);
                              mSplashImage.setVisibility(View.INVISIBLE);
                          }
                      } finally {
                          cursor.close();
                      }
                  } else if (uriString.startsWith("file://")) {
                      uploadFileName = fileToUpload.getName();
                      filename.setText(uploadFileName);
                      uploadFile.setVisibility(View.VISIBLE);
                      mEditText.setVisibility(View.VISIBLE);
                      mSplashImage.setVisibility(View.INVISIBLE);
                  }else {
                      filename.setText("Invalid file type");
                  }
              }else if (resultCode == RESULT_CANCELED){
                  Toast.makeText(this, "User Canceled File Request.", Toast.LENGTH_LONG).show();
              }else{
                  Toast.makeText(this, "File Request failed.", Toast.LENGTH_LONG).show();
              }
          } else{
                  Toast.makeText(this, "Error loading File. Please try again.", Toast.LENGTH_LONG).show();
              }
          }</code></pre>
  </div>
  </div>
  </p>
  
  <p>UPLOAD_URL:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>if (isset($_POST['media_id']) &amp;&amp; isset($_POST['file'])) {
   // receiving the post params
   $media_id = $_POST['media_id'];
   $filepath = $_POST['file'];
   
   if ($filepath != null){
   
   $file_path = "uploads/$media_id.pdf";
   $file = $_FILES['myFile']['name'];
   $file_tmp = $_FILES['myFile']['tmp_name'];
   $user = $db-&gt;storeFile($filepath, $media_id);
   
   move_uploaded_file($file_tmp, $file_path);
   
   $user = $db-&gt;storeFile($filepath, $media_id);
   
   if ($user) {
      // user stored successfully
             $response["error"] = FALSE;
             $response["file"]["media_id"] = $user["media_id"];
             echo json_encode($response);
         } else {
              // user failed to store
             $response["error"] = TRUE;
             $response["error_msg"] = "Unknown error occurred in upload!";
             echo json_encode($response);
          }
   }
  } else {
      $response["error"] = TRUE;
      $response["error_msg"] = "Error uploading file.";
      echo json_encode($response);
  }
  ?&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>storeFile function:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>  public function storeFile($file, $media_id) {
   
   $filename = "***.com/uploads/$media_id.pdf";
   
      $stmt = $this-&gt;conn-&gt;prepare("UPDATE files SET file=? WHERE media_id=?");
      $stmt-&gt;bind_param("ss", $filename, $media_id);
      $result = $stmt-&gt;execute();
      $stmt-&gt;close();
   
      // check for successful store
      if ($result) {
          $stmt = $this-&gt;conn-&gt;prepare("SELECT media_id FROM files WHERE media_id = ?");
          $stmt-&gt;bind_param("s", $media_id);
          $stmt-&gt;execute();
          $user = $stmt-&gt;get_result()-&gt;fetch_assoc();
          $stmt-&gt;close();
   
          return $user;
      } else {
          return false;
      }
  }</code></pre>
  </div>
  </div>
  </p>