Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/183.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Android文件未上载到服务器_Php_Android_Android File - Fatal编程技术网

Php Android文件未上载到服务器

Php Android文件未上载到服务器,php,android,android-file,Php,Android,Android File,我正在生成一个文件夹,在其中创建一个文本文件,并使用以下功能将其存储在缓存目录中: public void GenerateFile(String sFileName, String sBody){ try { String foldername="TestFolder"; File root = new File(context.getCacheDir() + "/"+foldername);

我正在生成一个文件夹,在其中创建一个文本文件,并使用以下功能将其存储在缓存目录中:

public void GenerateFile(String sFileName, String sBody){
        try
        {
            String foldername="TestFolder";
            File root = new File(context.getCacheDir() + "/"+foldername);
            if (!root.exists()) {
                root.mkdirs();
            }
            File gpxfile = new File(root, sFileName);
            FileWriter writer = new FileWriter(gpxfile);
            writer.append(sBody);
            writer.flush();
            writer.close();
            Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
        }
        catch(Exception e)
        {
           Log.d("Exception is",e.toString());
        }
    }
然后我尝试将此文件发布到服务器上,这是我的活动:

 GenerateFile("ConfigFile.txt","test\ndfssdfdsf\ndfsdsdfsfds\nsdfdfs");

uploadFilePath=this.getCacheDir() + "/TestFolder/ConfigFile.txt";
        upLoadServerUri = "http://www.*****.com/test/uploadtoserver.php";

        uploadButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {

                dialog = ProgressDialog.show(PostFile.this, "", "Uploading file...", true);

                new Thread(new Runnable()
                {
                    public void run()
                    {
                        runOnUiThread(new Runnable()
                        {
                            public void run()
                            {
                                messageText.setText("uploading started.....");
                            }
                        });

                        uploadFile(uploadFilePath);

                    }
                }).start();
            }
        });
    }

    public int uploadFile(String sourceFileUri)
    {


        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())
        {

            dialog.dismiss();

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

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("Source File not exist :" + uploadFilePath);
                }
            });

            return 0;

        }
        else
        {
            try
            {

                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                URL url = new URL(upLoadServerUri);

                // 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("myFile",fileName);
                Log.d("File Name is", fileName);
                dos = new DataOutputStream(conn.getOutputStream());

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


                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                        Log.d("Result is",String.valueOf(result));

                    }

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

                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"+" serverpath"
                                    +uploadFileName;

                            messageText.setText(msg);
                            Toast.makeText(PostFile.this, "File Upload Complete.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                }

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

            }
            catch (MalformedURLException ex)
            {

                dialog.dismiss();
                ex.printStackTrace();

                runOnUiThread(new Runnable()
                {
                    public void run()
                    {
                        messageText.setText("MalformedURLException Exception : check script url.");
                        Toast.makeText(PostFile.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                    }
                });

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

                dialog.dismiss();
                e.printStackTrace();

                runOnUiThread(new Runnable()
                {
                    public void run()
                    {
                        messageText.setText("Got Exception : see logcat ");
                        Toast.makeText(PostFile.this, "Got Exception : see logcat ",
                                Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("Upload Exception", "Exception : "
                        + e.getMessage(), e);
            }
            dialog.dismiss();
            return serverResponseCode;
这是php代码:

    <?php

    if (!empty($_FILES["myFile"])) {
        $myFile = $_FILES["myFile"];
        if ($myFile["error"] !== UPLOAD_ERR_OK) {
            echo "error";
        }
        else{
            $filename = $_FILES['myFile']['name'];
            $ext = pathinfo($filename, PATHINFO_EXTENSION);

            echo "success -- extension: ." . $ext;
        }
    }
    else{
        echo "no file found";
    }

?>


文件未上载,php页面未返回任何文件,是否有任何帮助?

您是否已验证用户apache(或运行php的用户)是否有权限写入$file\u path中指定的目录

将以下代码与PHP脚本放在同一目录中,然后在web浏览器中访问它

<?php

$file_path = 'uploads/';

$success = file_put_contents($file_path . "afile", "This is a test");

if($success === false) {
    echo "Couldn't write file";
} else {
    echo "Wrote $success bytes";
}

?>
试试这个。 我已经测试了这个代码,它的工作良好的图像上传


该错误是从此行生成的吗?回显“未找到文件”;尝试更改消息并确保尝试将其作为base64 Strings发送返回的消息是:14 bytestry将您的文件路径记录在android中,并确保您有权读取该文件我正在正常读取文件内容,这是路径:/data/data/com.example.test.myapplication/cache/TestFolder/ConfigFile.txt
// Get image string posted from Android App
$base = $_POST["image"];
// Get file name posted from Android App
$filename = $_POST["filename"];
// Decode Image
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
// Images will be saved under 'www/imgupload/uplodedimages' folder
$file = fopen($filename, 'wb');
// Create File
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete, Please check your php file directory';