文件未发现异常试图从Android应用程序上传文件到XAMPP服务器时, [英] File Not Found Exception when trying to upload file to xampp server from android application

查看:1048
本文介绍了文件未发现异常试图从Android应用程序上传文件到XAMPP服务器时,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Andr​​oid应用程序,我想通过搜索存储我的手机的附加文件,然后我试图把它上传到服务器。我可以搜索文件,并附上他们,而上传到服务器我收到未发现异常文件。 请帮我摆脱这个问题,请让我知道我缺少什么。如果有更好的方法去做请不要让我知道。

In my android application, I am trying to attach a file by searching storage of my phone and then I am trying to upload it to server. I am able to search for files and attach them, while uploading it to server I am getting File not found exception. Please help me to get out of this issue, please let me know what am I missing. If there is a better way to do please do let me know.

FileUtils.java:

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方法:

Search, Attach and uploadtoServer methods:

 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跟踪:

My Adb Logcat trace:

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脚本:

My PHP Script:

<?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;
}
?>

我能够获得所选择的文件名和同名我传递到上传文件。我在清单中的所有所需的权限。请让我知道我的错误。所有建议都欢迎。请让我知道如果有更多的细节是必需的。先谢谢了。

I am able to get the selected file name and the same name I am passing to the upload file. I have all the required permissions in manifest. Please let me know my mistake. All suggestions are welcome. Please let me know if more details are required. Thanks in advance.

推荐答案

最近我面临着同样的问题。我这是怎么固定的。

Recently I faced same issue. This is how i fixed.

它的所有关于权限应用于该文件夹中的 上传 。更改为777(使可写)

Its all about permissions to that folder uploads. change to 777(make writable)

这篇关于文件未发现异常试图从Android应用程序上传文件到XAMPP服务器时,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆