使用PHP脚本将文件从Android设备上传到00WebHost-正确的文件路径?

时间:2014-08-22 17:45:32

标签: php android web-services

在下面的AndroidPHP代码中,我尝试将手机中的小文本文件上传到00webhost server

该文件目前根本没有上传,代码中是否有syntax errors

我不知道在file/folder path中上传文件的00webhost是否正确?它是public_html吗?

请注意,在下面的android代码中:

 String urlServer = "serverpath.../handle_upload.php";
package com.example.fileservertest;

显然不是真正的网址,我不想公开展示它。

Android代码:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new UploadFileToServer().execute();

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    class UploadFileToServer extends AsyncTask<Void, Void, Void>{

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            HttpURLConnection connection = null;
            DataOutputStream outputStream = null;
            DataInputStream inputStream = null;

            File sdCard = Environment.getExternalStorageDirectory();
            //dir = new File(sdCard.getAbsolutePath() + "/Math Game files/");

            String pathToOurFile= sdCard.getAbsolutePath() + "/Math Game files/MathsGame-Attention1408652824573db015b01";
            String urlServer = "serverpath.../handle_upload.php";
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary =  "*****";

            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1*1024*1024;

            try
            {
                FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

                URL url = new URL(urlServer);
                connection = (HttpURLConnection) url.openConnection();

                // Allow Inputs &amp; Outputs.
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setUseCaches(false);

                // Set HTTP method to POST.
                connection.setRequestMethod("POST");

                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

                outputStream = new DataOutputStream( connection.getOutputStream() );
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
                outputStream.writeBytes(lineEnd);

                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0)
                {
                    outputStream.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }

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

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

                Log.d("Server response message", "Message [" + serverResponseMessage + "]");
                Log.d("Server response code", "Message [" + serverResponseCode + "]");
                fileInputStream.close();
                outputStream.flush();
                outputStream.close();
            }
            catch (Exception ex)
            {
                //Exception handling
            }

            return null;
        }

    }
}

对应PHP脚本:

<?php
$target_path  = ".\";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
{
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
 " has been uploaded";
} 
else
{
    echo "There was an error uploading the file, please try again!";
}

?取代;

运行Android代码时

当前 Logcat输出

08-22 18:45:00.498: W/ApplicationPackageManager(25637): getCSCPackageItemText()
08-22 18:45:00.578: I/Adreno-EGL(25637): <qeglDrvAPI_eglInitialize:381>: EGL 1.4 QUALCOMM build:  (CL3869936)
08-22 18:45:00.578: I/Adreno-EGL(25637): OpenGL ES Shader Compiler Version: 17.01.11.SPL
08-22 18:45:00.578: I/Adreno-EGL(25637): Build Date: 01/17/14 Fri
08-22 18:45:00.578: I/Adreno-EGL(25637): Local Branch: 
08-22 18:45:00.578: I/Adreno-EGL(25637): Remote Branch: 
08-22 18:45:00.578: I/Adreno-EGL(25637): Local Patches: 
08-22 18:45:00.578: I/Adreno-EGL(25637): Reconstruct Branch: 
08-22 18:45:00.608: D/OpenGLRenderer(25637): Enabling debug mode 0

0 个答案:

没有答案