如何通过PHP同时从android发送数据和图像

时间:2012-12-11 03:16:46

标签: android

在我成功发送数据和图像之前,它是通过两个不同的程序完成的

这是我发送数据的代码

public class HTTPPostData扩展了AsyncTask {

    @Override
    protected String doInBackground(String... urls) {
        String Result = "";
        byte[] Bresult = null;
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(URL_TO_LOAD);
        try {
            List<NameValuePair> nameValuePairs = LPD;
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            HttpResponse response = client.execute(post);
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
                Bresult = EntityUtils.toByteArray(response.getEntity());
                Result = new String(Bresult, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }
        return Result;
    }

    protected void onPostExecute(String result) {
        // dismiss the dialog after the file was downloaded
        if (!result.toString().trim().equals("")) {
            RunProcedure.StrParam = result;
            RunProcedure.run();
        }
    }
}

这是我的代码转移pic

public boolean TransferFileToHttp(String address_to_handle, String file_name) {
    boolean result = false;
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    // DataInputStream inputStream = null;

    String pathToOurFile = file_name;
    String urlServer = address_to_handle;
    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 & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // Enable POST method
        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();

        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
        result = true;
    } catch (Exception ex) {
        // Exception handling
        result = false;
    }
    return result;
}

如何将传输文件过程加入到发布数据过程并检索字符串作为结果?

1 个答案:

答案 0 :(得分:1)

绝对有可能这样做。但是,您必须执行一些额外的步骤。

首先,您必须将图像转换为基本64字符串。请参阅此文档 http://developer.android.com/reference/android/util/Base64.html

现在该字符串可以作为常规json数据发送。

在服务器端,您需要一种机制将base64字符串转换回图像。但这是一项微不足道的任务。

这种方法有一些缺点,例如json请求的大小和编码/解码的额外开销。