尝试从Android应用程序

时间:2015-06-17 05:17:23

标签: java php android mysql file-upload

在我的Android应用程序中,我试图通过搜索我的手机存储来附加文件,然后我尝试将其上传到服务器。我能够搜索文件并附加它们,同时将其上传到服务器我收到文件未找到异常。 请帮我解决这个问题,请让我知道我错过了什么。如果有更好的方法,请告诉我。

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

搜索,附加和上传到服务器方法:

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

我的Adb 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;
}
?>

我能够获取所选的文件名和我传递给上传文件的相同名称。我在清单中拥有所有必需的权限。请让我知道我的错误。欢迎所有建议。如果需要更多详细信息,请与我们联系。提前谢谢。

1 个答案:

答案 0 :(得分:0)

最近我遇到了同样的问题。这就是我修复的方式。

该文件夹的所有权限 uploads 。改为777(可写)