将图像上载到服务器时,权限被拒绝错误

时间:2016-11-26 16:15:04

标签: java php android

在我的应用程序中,我尝试拍照并将其发送到编码为字符串的服务器,当我运行它时,我能够拍照,但是一旦我点击确定应用程序崩溃并且我收到以下错误:

E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Pictures/test123.jpeg: open failed: EACCES (Permission denied)
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                  Process: info.androidhive.loginandregistration, PID: 8775
                  java.lang.RuntimeException: An error occurred while executing doInBackground()
                      at android.os.AsyncTask$3.done(AsyncTask.java:309)
                      at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                      at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                      at java.lang.Thread.run(Thread.java:818)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
                      at info.androidhive.loginandregistration.activity.ImageActivity$Encode_image.doInBackground(ImageActivity.java:86)
                      at info.androidhive.loginandregistration.activity.ImageActivity$Encode_image.doInBackground(ImageActivity.java:79)
                      at android.os.AsyncTask$2.call(AsyncTask.java:295)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
                      at java.lang.Thread.run(Thread.java:818) 

继承我的代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.loginandregistration"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-feature android:name="android.hardware.Camera" android:required="true"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:name="info.androidhive.loginandregistration.app.AppController"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".activity.LoginActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop"
            android:windowSoftInputMode="adjustPan" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activity.RegisterActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop"
            android:windowSoftInputMode="adjustPan" />
        <activity
            android:name=".activity.MainActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop" />
        <activity
            android:name=".activity.test"
            android:label="@string/app_name"
            android:launchMode="singleTop" />
        <activity
            android:name=".activity.SearchActivity"
            android:label="MY SICK APP"
            android:launchMode="singleTop" />
        <activity
            android:name=".activity.ImageActivity"
            android:label="MY SICK APP"
            android:launchMode="singleTop"
            android:largeHeap="true"/>
    </application>

</manifest>

-

public class ImageActivity extends Activity{
    final String URL = "linktophpfile";
    private Button button;
    private String coded_string, name;
    private Bitmap bitmap;
    private File file;
    private Uri uri;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_main);

        button = (Button) findViewById(R.id.bt_main);
        button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick (View view){
                Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                getUri();
                i.putExtra(MediaStore.EXTRA_OUTPUT,uri);
                startActivityForResult(i,5);
            }
        });

    }

    public void getUri() {
        String name = "test123.jpeg";
        file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+ file.separator + name);
        uri = Uri.fromFile(file);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==5 && resultCode== RESULT_OK){
            new Encode_image().execute();

        }
    }

    private class Encode_image extends AsyncTask<Void,Void,Void> {

        @Override
        protected Void doInBackground(Void... voids) {

            bitmap = BitmapFactory.decodeFile(uri.getPath());
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
            bitmap.recycle();

            byte[] array = stream.toByteArray();
            coded_string = Base64.encodeToString(array,0);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            makeRequest();
        }
    }

    private void makeRequest() {
        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest request = new StringRequest(Request.Method.POST,URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

            }
        }, new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error){

            }

        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError{

                HashMap<String, String> map = new HashMap<>();
                map.put("coded_String", coded_string);
                map.put("image_name", name);
                return map;
            }
        };
        queue.add(request);


    }

}

php代码:

<?php
 header('Content-type : bitmap; charset=utf-8');

 if(isset($_POST["encoded_string"])){

    $encoded_string = $_POST["encoded_string"];
    $image_name = $_POST["image_name"];

    $decoded_string = base64_decode($encoded_string);

    $path = 'images/'.$image_name;

    $file = fopen($path, 'wb');

    $is_written = fwrite($file, $decoded_string);
    fclose($file);

    if($is_written > 0) {

        $connection = mysqli_connect('localhost', 'username', 'password','dbname');
        $query = "INSERT INTO images(name,path) values('$image_name','$path');";

        $result = mysqli_query($connection, $query) ;

        if($result){
            echo "success";
        }else{
            echo "failed";
        }

        mysqli_close($connection);
    }
 }
?>

任何可能出错的想法?感谢

2 个答案:

答案 0 :(得分:0)

确保你有

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

manifest.xml文件中声明

答案 1 :(得分:0)

1在手机设置中查看您应用的权限状态。 2在调试模式下查看此照片的真实uri。