首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未找到FileNotFoundException安卓文件

未找到FileNotFoundException安卓文件
EN

Stack Overflow用户
提问于 2021-10-03 07:42:44
回答 1查看 118关注 0票数 0

嗨,我正在尝试上传一个文件从我的android设备到我的服务器。在我的虚拟设备上,一切都工作得很完美,但是在我的实际设备上,我总是得到一个没有找到错误的文件。下面是我的代码,请有人帮我

代码语言:javascript
复制
public int uploadFile(final String selectedFilePath) {

    int serverResponseCode = 0;

    HttpURLConnection connection;
    DataOutputStream dataOutputStream;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";


    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File selectedFile = new File(selectedFilePath);


    String[] parts = selectedFilePath.split("/");
    final String fileName = parts[parts.length - 1];

    if (!selectedFile.isFile()) {
        dialog.dismiss();

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath);
            }
        });
        return 0;
    } else {
        try {

            FileInputStream fileInputStream = new FileInputStream(selectedFile);

            URL url = new URL(SERVER_URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);//Allow Inputs
            connection.setDoOutput(true);//Allow Outputs
            connection.setUseCaches(false);//Don't use a cached Copy
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty(
                    "Content-Type", "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("uploaded_file",selectedFilePath);

            //creating new dataoutputstream
            dataOutputStream = new DataOutputStream(connection.getOutputStream());

            //writing bytes to data outputstream
            dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
            dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + selectedFilePath + "\"" + lineEnd);

            dataOutputStream.writeBytes(lineEnd);

            //returns no. of bytes present in fileInputStream
            bytesAvailable = fileInputStream.available();
            //selecting the buffer size as minimum of available bytes or 1 MB
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            //setting the buffer as byte array of size of bufferSize
            buffer = new byte[bufferSize];

            //reads bytes from FileInputStream(from 0th index of buffer to buffersize)
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);


            //loop repeats till bytesRead = -1, i.e., no bytes are left to read
            while (bytesRead > 0) {

                try {
                    //write the bytes read from inputstream
                    dataOutputStream.write(buffer, 0, bufferSize);
                } catch (OutOfMemoryError e) {
                    Toast.makeText(createindiv.this, "Insufficient Memory!", Toast.LENGTH_SHORT).show();
                }
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            dataOutputStream.writeBytes(lineEnd);
            dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            try{
                serverResponseCode = connection.getResponseCode();
            }catch (OutOfMemoryError e){
                Toast.makeText(createindiv.this, "Memory Insufficient!", Toast.LENGTH_SHORT).show();
            }
            String serverResponseMessage = connection.getResponseMessage();

            Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);

            //response code of 200 indicates the server status OK
            if (serverResponseCode == 200) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        names=    name.getText().toString();
                        aboutz =  about.getText().toString();

                        createindivads loadm = new createindivads();
                        loadm.execute(names, aboutz, username, fileName,"");

                        tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "https://waksmat.com/api/videos/" + fileName);
                    }
                });
            }

            //closing the input and output streams
            fileInputStream.close();
            dataOutputStream.flush();
            dataOutputStream.close();

            if (wakeLock.isHeld()) {

                wakeLock.release();
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(createindiv.this, "File Not Found", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(createindiv.this, "URL Error!", Toast.LENGTH_SHORT).show();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(createindiv.this, "Cannot Read/Write File", Toast.LENGTH_SHORT).show();
                }
            });
        }
        dialog.dismiss();
        return serverResponseCode;
    }

}

在我的日志猫中,我得到了我的绝对路径字符串,我可以看到文件是存储的,它说。我正在使用sdk 29开发应用程序。

下面是我的日志猫

I/chatty: uid=10070(brianyobra.bramcode.thuo) FinalizerDaemon完全相同1行W/System:资源未能调用end。E/eglCodecCommon: goldfish_dma_create_region:无法获得设备fd!fd -1 Path:/storage/emulated/0/DCIM/Camera/IMG_20210826_061358.jpg I/MainActivity:选定的文件errno=2 I/MainActivity:服务器响应为: OK: 200

EN

回答 1

Stack Overflow用户

发布于 2021-10-03 09:54:37

我发现了我的错误。我没有在我的android宣言(android:requestLegacyExternalStorage=“真”)中放上这个小代码片段,谢谢你帮助我。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69422966

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档