繁体   English   中英

Android文件未上传到服务器

[英]Android File not being uploaded to server

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

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

?>

这会给出成功消息还是错误消息?

如果显示错误消息,请尝试更改上载目录的所有权。

尝试这个。 我已经测试过此代码,可以很好地上传图片

// 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';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM