Файл не найден Исключение при попытке загрузить файл на сервер xampp из приложения android

В моем приложении для Android я пытаюсь прикрепить файл, выполнив поиск в хранилище своего телефона, а затем попытаюсь загрузить его на сервер. Я могу искать файлы и прикладывать их, а при загрузке на сервер я получаю исключение File not found. Пожалуйста, помогите мне выйти из этой проблемы, пожалуйста, дайте мне знать, что мне не хватает. Если есть лучший способ сделать, пожалуйста, дайте мне знать.

FileUtils.java:

import android.content.Context; import android.database.Cursor; import android.net.Uri; import java.net.URISyntaxException; /** * Created by iFocus on 6/16/2015. */ public class FileUtils { public static String getPath(Context context, Uri uri) throws URISyntaxException { if ("content".equalsIgnoreCase(uri.getScheme())) { String[] projection = { "_data" }; Cursor cursor = null; try { cursor = context.getContentResolver().query(uri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow("_data"); if (cursor.moveToFirst()) { return cursor.getString(column_index); } } catch (Exception e) { // Eat it } } else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } } 

Методы поиска, присоединения и uploadtoServer:

  private void showFileChooser() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); try { startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE); Toast.makeText(getActivity(), "Please install a File Manager.", Toast.LENGTH_SHORT).show(); } catch (android.content.ActivityNotFoundException ex) { // Potentially direct the user to the Market with a Dialog } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case FILE_SELECT_CODE: if (resultCode == RESULT_OK) { // Get the Uri of the selected file Uri uri = data.getData(); Log.d("iFocus", "The value of data is " + data); Log.d("TAG", "File Uri: " + uri.toString()); fileName = uri.toString(); selectedFileName.setText(uri.toString()); // Get the path String path = null; try { path = FileUtils.getPath(getActivity(), uri); } catch (URISyntaxException e) { e.printStackTrace(); } Log.d("TAG", "File Path: " + path); // Get the file instance // File file = new File(path); // Initiate the upload } break; } super.onActivityResult(requestCode, resultCode, data); } private void doFileUpload() { HttpURLConnection conn = null; DataOutputStream dos = null; InputStreamReader inStream = null; String existingFileName = fileName; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String responseFromServer = ""; String urlString = "http://192.168.1.21/uploadToServer.php"; try { //------------------ CLIENT REQUEST FileInputStream fileInputStream = new FileInputStream(new File(fileName)); // open a URL connection to the Servlet URL url = new URL(urlString); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + 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 > 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); // close streams Log.e("Debug", "File is written"); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { Log.e("Debug", "error: " + ex.getMessage(), ex); } catch (IOException ioe) { Log.e("Debug", "error: " + ioe.getMessage(), ioe); } //------------------ read the SERVER RESPONSE BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; // Read Server Response while ((line = reader.readLine()) != null) { // Append server response in string sb.append(line); } String str ; str = sb.toString(); Log.d("iFocus", "The value of str is " +str); inStream.close(); } catch (IOException ioex) { Log.e("Debug", "error: " + ioex.getMessage(), ioex); } } 

Моя трассировка Logcat:

 06-17 10:43:21.484 16788-16788/com.blo.ifo.ifocusblogs E/Debug﹕ error: content:/com.android.providers.downloads.documents/document/1541: open failed: ENOENT (No such file or directory) java.io.FileNotFoundException: content:/com.android.providers.downloads.documents/document/1541: open failed: ENOENT (No such file or directory) at libcore.io.IoBridge.open(IoBridge.java:456) at java.io.FileInputStream.<init>(FileInputStream.java:76) at com.blo.ifo.ifocusblogs.InsertAndroidPost.doFileUpload(InsertAndroidPost.java:267) at com.blo.ifo.ifocusblogs.InsertAndroidPost.access$400(InsertAndroidPost.java:50) at com.blo.ifo.ifocusblogs.InsertAndroidPost$InsertServerAndroidAdminPost.onPostExecute(InsertAndroidPost.java:539) at com.blo.ifo.ifocusblogs.InsertAndroidPost$InsertServerAndroidAdminPost.onPostExecute(InsertAndroidPost.java:445) at android.os.AsyncTask.finish(AsyncTask.java:636) at android.os.AsyncTask.access$500(AsyncTask.java:177) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory) at libcore.io.Posix.open(Native Method) at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186) at libcore.io.IoBridge.open(IoBridge.java:442)            at java.io.FileInputStream.<init>(FileInputStream.java:76)            at com.blo.ifo.ifocusblogs.InsertAndroidPost.doFileUpload(InsertAndroidPost.java:267)            at com.blo.ifo.ifocusblogs.InsertAndroidPost.access$400(InsertAndroidPost.java:50)            at com.blo.ifo.ifocusblogs.InsertAndroidPost$InsertServerAndroidAdminPost.onPostExecute(InsertAndroidPost.java:539)            at com.blo.ifo.ifocusblogs.InsertAndroidPost$InsertServerAndroidAdminPost.onPostExecute(InsertAndroidPost.java:445)            at android.os.AsyncTask.finish(AsyncTask.java:636)            at android.os.AsyncTask.access$500(AsyncTask.java:177)            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)            at android.os.Handler.dispatchMessage(Handler.java:102)            at android.os.Looper.loop(Looper.java:135)            at android.app.ActivityThread.main(ActivityThread.java:5254)            at java.lang.reflect.Method.invoke(Native Method)            at java.lang.reflect.Method.invoke(Method.java:372)            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 06-17 10:43:21.484 16788-16788/com.blo.ifo.ifocusblogs D/AndroidRuntime﹕ Shutting down VM 06-17 10:43:21.487 16788-16788/com.blo.ifo.ifocusblogs E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.blo.ifo.ifocusblogs, PID: 16788 java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.InputStream java.net.HttpURLConnection.getInputStream()' on a null object reference at com.blo.ifo.ifocusblogs.InsertAndroidPost.doFileUpload(InsertAndroidPost.java:322) at com.blo.ifo.ifocusblogs.InsertAndroidPost.access$400(InsertAndroidPost.java:50) at com.blo.ifo.ifocusblogs.InsertAndroidPost$InsertServerAndroidAdminPost.onPostExecute(InsertAndroidPost.java:539) at com.blo.ifo.ifocusblogs.InsertAndroidPost$InsertServerAndroidAdminPost.onPostExecute(InsertAndroidPost.java:445) at android.os.AsyncTask.finish(AsyncTask.java:636) at android.os.AsyncTask.access$500(AsyncTask.java:177) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

Мой скрипт PHP:

 <?php // Where the file is going to be placed $target_path = "uploads/"; /* Add the original filename to our target path. Result is "uploads/filename.extension" */ $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; chmod ("uploads/".basename( $_FILES['uploadedfile']['name']), 0644); } else{ echo "There was an error uploading the file, please try again!"; echo "filename: " . basename( $_FILES['uploadedfile']['name']); echo "target_path: " .$target_path; } ?> 

Я могу получить выбранное имя файла и одно и то же имя, которое я передаю в файл загрузки. У меня есть все необходимые разрешения в манифесте. Пожалуйста, дайте мне знать мою ошибку. Все предложения приветствуются. Пожалуйста, дайте мне знать, если требуется более подробная информация. Заранее спасибо.

Недавно я столкнулся с такой же проблемой. Вот как я исправил.

Его все о разрешениях на uploads этой папки. изменить на 777 (сделать доступным для записи)