android php与多部分数据一起发送字符串

时间:2015-10-04 15:48:00

标签: php android

我使用以下代码将图像/视频发送到php服务器:

FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);

HttpURLConnection 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("uploaded_file", fileName); 

DataOutputStream 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
int bytesAvailable = fileInputStream.available(); 

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

// read file and write it into form...
int 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);

在PHP中接收:

<?php

    $file_path = "uploads/";

    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }
 ?>

现在,我还想将一个字符串发送到服务器。

示例: - 名称:&#34;用户&#34;,值:&#34; abc&#34;

这样我就可以在PHP中获取它:

$value = $_POST["user"]

如何将这样的字符串添加到输出流中以便在php中接收?

3 个答案:

答案 0 :(得分:1)

我是用它做的:

FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);

HttpURLConnection 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("uploaded_file", fileName); 

DataOutputStream 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
int bytesAvailable = fileInputStream.available(); 

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

// read file and write it into form...
int 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 + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"user\"" + lineEnd);

dos.writeBytes(lineEnd);

dos.writeBytes(this_number);

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);

答案 1 :(得分:0)

其中一种方法是发送字符串以及由唯一分隔符分隔的内容处置( $

Content-Disposition: form-data; name="uploaded_file";filename=""+ fileName +"_$_stringdata"+ """ + lineEnd

在PHP中,http://php.net/manual/en/httpresponse.getcontentdisposition.php

使用getContentDisposition并解析它。

Description

static string HttpResponse::getContentDisposition ( void )
Get current Content-Disposition setting.


其他方式:使用httpmime 只需在您的MultipartEntity中添加一些FormBodyPart即可。

您可以使用StringBody对象来提供值。

以下是如何使用它的示例:

byte[] data = {10,10,10,10,10}; 
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("server url");
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("image", bab);

FormBodyPart bodyPart=new FormBodyPart("formVariableName", new StringBody("formValiableValue"));
reqEntity.addPart(bodyPart);
bodyPart=new FormBodyPart("formVariableName2", new StringBody("formValiableValue2"));
reqEntity.addPart(bodyPart);
bodyPart=new FormBodyPart("formVariableName3", new StringBody("formValiableValue3"));
reqEntity.addPart(bodyPart); 
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while((line = in.readLine()) != null) {
    System.out.println(line);
}

在php中:

$_FILES
Array
(
    [image] => Array
        (
            [name] => image.jpg
            [type] => application/octet-stream
            [tmp_name] => /tmp/php6UHywL
            [error] => 0
            [size] => 5
        )

)
$_POST:
Array
(
    [formVariableName] => formValiableValue
    [formVariableName2] => formValiableValue2
    [formVariableName3] => formValiableValue3
)

答案 2 :(得分:0)

在搜索了大量资源后,我什么都没有,但是当我尝试从$ _SERVER超级全局变量中获取文本数据时,我得到了所有文本数据和$ _FILE以获取图像。

以下是为android和php端提供的代码

package com.example.kingmash.Helper;


import android.content.Context;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.example.kingmash.DAO.Profile_cover;
import com.example.kingmash.DAO.User_profile_cover;
import com.example.kingmash.MainActivity;
import com.example.kingmesh.R;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import static com.example.kingmash.Helper.AllRequest.responseMessage;

public class UploadFileOnlyAsync extends AsyncTask<String, Void, String> {
    String sourceFileUri, serverResponseMessage;
    int serverResponseCode;
    ProgressBar progressBar;
    User_profile_cover upc;
    int isdatainserted;
    Context context;

    public UploadFileOnlyAsync(Context context, String sourceFileUri, boolean requireprgressbar, User_profile_cover upc) {
        this.sourceFileUri = sourceFileUri;
        this.context = context;
        progressBar = null;
        this.upc = upc;
        if (requireprgressbar) {
//            progressBar = ((AppCompatActivity) context).findViewById(R.id.progressbar);
        }

    }

    @Override
    protected void onPreExecute() {
        Log.d("on pre----", "on pre-----------");
        if (progressBar != null) {
            progressBar.setVisibility(View.GONE);
            progressBar.setVisibility(View.VISIBLE);
        }


    }

    @Override
    protected void onProgressUpdate(Void... values) {

        Log.d("On update-------------", "" + values[0]);

        if (progressBar != null) {
            progressBar.setProgress(Integer.parseInt(values[0].toString()));
        }

    }

    @Override
    protected String doInBackground(String... params) {
        responseMessage = new Profile_cover(context).insert(upc, Routes.insertStepsURL);
        if (responseMessage.get(0).equals("Inserted")) {
            Log.d("key------insert fata", "" + isdatainserted);
            try {
                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()) {
                    try {
                        String upLoadServerUri = Routes.update_prfile_covrer_URL;
                        // open a URL connection to the Servlet
                        FileInputStream fileInputStream = new FileInputStream(sourceFile);
                        URL url = new URL(upLoadServerUri);
                        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                        StrictMode.setThreadPolicy(policy);
                        // 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("user_id", "1");
                        dos = new DataOutputStream(conn.getOutputStream());

                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data; name=\"profile\";filename=\""
                                + sourceFileUri + "\"" + 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();
                        serverResponseMessage = conn
                                .getResponseMessage();

                        if (serverResponseCode == 200) {

                            // messageText.setText(msg);
                            //Toast.makeText(ctx, "File Upload Complete.",
                            //      Toast.LENGTH_SHORT).show();

                            // recursiveDelete(mDirectory1);

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

                        String line;
                        ArrayList responseMessage = new ArrayList();
                        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        while ((line = br.readLine()) != null) {
                            Log.d("line---", line);
                            responseMessage.add(line);
                        }

                    } catch (Exception e) {

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

                    }
                    // dialog.dismiss();

                } // End else block


            } catch (Exception ex) {
                // dialog.dismiss();

                ex.printStackTrace();
            }
        }
        Log.d("do in back-------------", "" + "Executed " + serverResponseMessage + "" + serverResponseCode + responseMessage);

        return "Executed " + serverResponseMessage + "" + serverResponseCode + "  " + responseMessage;
    }

    @Override
    protected void onPostExecute(String result) {
        if (progressBar != null) {
            progressBar.setVisibility(View.GONE);
        }
    }


}

这是从$ _SERVER或getAllHeaders()函数读取标头的php代码

<?php
session_start();
include '../Config/ConnectionObjectOriented.php';
include '../Config/DB.php';
$db = new DB($conn);
$info=$db->fileUploadWithTable($_FILES,"user_profile_cover",$user_id,"../img/user", "5m", "jpg,png");
echo $info[0];
echo $info[1];

// you can check the detail of header by this code

foreach (getallheaders() as $name => $value) { 
    echo "$name: $value <br>"; 
}