java - 无法访问内部存储中的文件

标签 java android storage

我正在尝试构建一个 Activity ,允许用户在他的画廊中选择一张图片并将其发送到我的 Web 服务器(它完美地从另一个 php 网页接收文件)。 问题是:在应用程序尝试发出请求之前,代码返回错误:无法访问该文件。

在更改代码之前,我有

EACESS(Permissions Denied)

现在我只有代码打印的内容了。

E/uploadFile: Source File not exist :

这是我的代码:

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {

        final Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        new Thread(new Runnable() {
            public void run() {
                runOnUiThread(new Runnable() {
                    public void run() {
                    }
                });

                uploadFile(selectedImage.toString());

            }
        }).start();
    }
}
public int uploadFile(String sourceFileUri) {

    verifyStoragePermissions(ScanActivity.this);
    String fileName = sourceFileUri;

    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(sourceFileUri);

    if (!sourceFile.isFile()) {


        Log.e("uploadFile", "Source File not exist :");

        runOnUiThread(new Runnable() {
            public void run() {
            }
        });

        return 0;

    }
    else
    {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL("http://82.237.124.168/Legimetrie/reception_intervention_scan.php");

            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", fileName);

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"fileToUpload\";filename=\""
                            + fileName + "\"" + 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);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if(serverResponseCode == 200){

                runOnUiThread(new Runnable() {
                    public void run() {

                        String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                +" http://www.androidexample.com/media/uploads/";

                        Toast.makeText(ScanActivity.this, "File Upload Complete.",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }

            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(ScanActivity.this, "MalformedURLException",
                            Toast.LENGTH_SHORT).show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(ScanActivity.this, "Got Exception : see logcat ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload file", "Exception : "
                    + e.getMessage(), e);
        }
        return serverResponseCode;

    } // End else block
}

这是我的 list 文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.partenaires.legimetrie.legimetrieapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".InscriptionActivity" />
    <activity android:name=".ConnexionActivity" />
    <activity android:name=".ServicesActivity" />
    <activity android:name=".InterventionRapideActivity" />
    <activity android:name=".InterventionDetailleeActivity" />
    <activity android:name=".ScanActivity" />
    <activity android:name=".ContactActivity"></activity>
</application>

你能帮我解决这个错误吗?

(PS:我想准确地说,我不想访问外部存储,但错误(我猜)是外部访问(权限被拒绝),所以我做错了)

最佳答案

从 Android M 版本开始,您需要在运行时请求某些权限。这应该对您有帮助:

Storage permission error in Marshmallow

关于java - 无法访问内部存储中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39192007/

相关文章:

java - Web/J2EE 和客户端应用程序的端到端分析

java - 从 JPMML 模型的 InputField 获取实际字段名称

java - 使用包含可编辑 JTextArea 的 JPanel 呈现 JTree 叶

java - 检索 ParseUser 的 ParseFile 时出现问题

android - 安装失败更新不兼容 : Package signatures do not match the previously installed version; ignoring

java - 如何在不更改前一个字符串的情况下使用拆分字符串

cloud - 了解 EMC ECS 和 EMC ScaleIO 之间的区别

java - 如何使用 CDI 集成将 robots.txt 添加到 Vaadin 7 应用程序?

android - Android中的Qt和app数据存储

ruby - 使用 Heroku 存储和处理大型 XML 文件?