如何在android中将字符串和文件发送到PHP?

时间:2017-03-17 05:53:02

标签: php android

我有这段代码:

  <?php


    require_once('dbconnect.php');


    $appName = $_POST['appName'];
    $acctID = $_POST['acctID'];

    $file_path = "app_files/";
    $filename = basename( $_FILES['uploaded_file']['name']);
    $extension = pathinfo($filename, PATHINFO_EXTENSION);

        $newFilePath = $file_path . $acctID . '_' . $appName . '_' . 'file.' . $extension;
        if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $newFilePath)) {
            echo "10";
        } else{
            echo "5";
        }



?>

我只能使用内容类型为multipart的POST方法(HTTPUrlConnection)发送文件。我的问题是,如何为$appName$acctID发送值?

 public class FileHandler {
String response;
DataOutputStream dataOutputStream;
public String  uploadFile(final String selectedFilePath , HashMap<String, Object> postDataParams){

    int serverResponseCode = 0;

    HttpURLConnection connection;
    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];

        try{
            FileInputStream fileInputStream = new FileInputStream(selectedFile);
            URL url = new URL(DataClass.localAddress + "/android_php/app_upload_step4.php");
            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){
                //write the bytes read from inputstream
                dataOutputStream.write(buffer,0,bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                bytesRead = fileInputStream.read(buffer,0,bufferSize);
            }

            serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

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

            //response code of 200 indicates the server status OK
            if (serverResponseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line="";
                while((line = br.readLine()) != null) {
                    response =  line;
                }
                System.out.println(response);
                //  response = br.readLine();

            }
            else {
                response="Error" + serverResponseCode;
            }

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



        } catch (FileNotFoundException e) {
            e.printStackTrace();


        } catch (MalformedURLException e) {
            e.printStackTrace();


        } catch (IOException e) {
            e.printStackTrace();
        }

            return response;


}

^ 上面的代码是我用来发送文件到PHP。

0 个答案:

没有答案