Android PHP发送字符串和多部分数据


android php send string alongwith multipart data

我正在发送图像/视频到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";
    }
 ?>

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

示例:—name: "user", value: "abc"

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

$value = $_POST["user"]

如何将这样的字符串添加到输出流中以在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 + 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);

一种方法是发送字符串和内容配置,用唯一的分隔符($)

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只需添加一些FormBodyPart到您的multiparentity。

您可以使用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
)

搜索大量资源后,我一无所获,但当我试图从$_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);
        }
    }

}

这里是php代码从$_SERVER或getAllHeaders()函数读取头信息

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