Android:上传文件并一起填写POST正文

发布于 2024-12-28 12:12:11 字数 1246 浏览 1 评论 0原文

我确实使用 MultipartEntity 将文件发送到服务器,它在 $_FILES superglobal 中正确显示

但我还需要填写 POST 正文以通过 php://stdin 读取

如何我这样做?

当前代码片段如下:

ByteArrayOutputStream bos = new ByteArrayOutputStream(); // stream to hold image
bm.compress(CompressFormat.JPEG, 75, bos); //compress image
byte[] data = bos.toByteArray(); 
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("REMOTE ADDRESS");
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE); // is this one causing trouble?
reqEntity.addPart("image", bab); // added image to request
// tried this with no luck
// reqEntity.addPart("", new StringBody("RAW DATA HERE")); 
postRequest.setEntity(reqEntity); // set the multipart entity to http post request
HttpResponse response = httpClient.execute(postRequest);

MultipartEntity 是 HttpMime 4.1.2 API 的一部分,文档

与此类似:Android:将文件与其他 POST 字符串一起上传到页面

I do use MultipartEntity to send File to server, it appears correctly in $_FILES superglobal

But I need also fill in POST body to be read via php://stdin

How can I do that?

current snippet below:

ByteArrayOutputStream bos = new ByteArrayOutputStream(); // stream to hold image
bm.compress(CompressFormat.JPEG, 75, bos); //compress image
byte[] data = bos.toByteArray(); 
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("REMOTE ADDRESS");
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE); // is this one causing trouble?
reqEntity.addPart("image", bab); // added image to request
// tried this with no luck
// reqEntity.addPart("", new StringBody("RAW DATA HERE")); 
postRequest.setEntity(reqEntity); // set the multipart entity to http post request
HttpResponse response = httpClient.execute(postRequest);

MultipartEntity is part of HttpMime 4.1.2 API, documentation

Similar to this: Android: Uploading a file to a page along with other POST strings

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

波浪屿的海角声 2025-01-04 12:12:11

只需添加一些 FormBodyPart到您的 MultipartEntity

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

这不会压缩一个内容主体部分内的所有帖子变量,但它完成了这项工作。

您无法从 php://stdin$HTTP_RAW_POST_DATA,两者均不适用于 multipart/form-data 编码。来自 PHP 文档:

php://input 是一个只读流,允许您读取原始数据
来自请求正文。对于 POST 请求,最好
使用 php://input 而不是 $HTTP_RAW_POST_DATA 因为它不
取决于特殊的 php.ini 指令。此外,对于那些情况
$HTTP_RAW_POST_DATA 默认情况下不填充,它是一个潜在的
内存密集程度较低的激活替代方案
始终填充原始帖子数据。 php://input 不可用
enctype="multipart/form-data"。

即使您设置 always_populate_raw_post_data 到 On 仍然无法解决问题:

始终填充包含原始 POST 数据的 $HTTP_RAW_POST_DATA。
否则,该变量仅填充无法识别的 MIME 类型
的数据。但是,访问原始 POST 的首选方法
数据是 php://input。 $HTTP_RAW_POST_DATA 不适用于
enctype="multipart/form-data"。

我最好的猜测是将所有数据添加为 ByteArrayBodyStringBody 只是
使用它就像从 php://stdin 中阅读一样

这是 ByteArrayBody

String testString="b=a&c=a&d=a&Send=Send";
reqEntity.addPart(new FormBodyPart("formVariables", new ByteArrayBody(testString.getBytes(), "application/x-www-form-urlencoded", "formVariables")));

在 PHP 中:

var_dump(file_get_contents($_FILES['formVariables']['tmp_name']));

您应该得到:

字符串(21)“b=a&c=a&d=a&Send=发送”

编辑:经过一番思考,我认为最好只使用一个 StringBody 并将所有数据放入一个 post 变量中,然后从那里解析它,它跳过将数据写入文件并在请求后删除它,因为临时文件完全无用,这将提高性能。
这是一个例子:

String testString="b=a&c=a&d=a&Send=Send";
bodyPart=new FormBodyPart("rawData", new StringBody(testString));
reqEntity.addPart(bodyPart);

然后从 PHP:

var_dump($_POST['rawData']);

Just add a a few FormBodyPart to your MultipartEntity.

You can use the StringBody object to provide the value.

Here is an example of how you can use it:

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

Here is the output of the PHP script:

$_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
)

This doesn't compress all the post vars inside of one content body part but it dose the job.

You can't access the data from php://stdin or $HTTP_RAW_POST_DATA, both are unavailable for multipart/form-data encoding. From the PHP docs:

php://input is a read-only stream that allows you to read raw data
from the request body. In the case of POST requests, it is preferable
to use php://input instead of $HTTP_RAW_POST_DATA as it does not
depend on special php.ini directives. Moreover, for those cases where
$HTTP_RAW_POST_DATA is not populated by default, it is a potentially
less memory intensive alternative to activating
always_populate_raw_post_data. php://input is not available with
enctype="multipart/form-data".

Even if you set always_populate_raw_post_data to On it still won't fix the problem:

Always populate the $HTTP_RAW_POST_DATA containing the raw POST data.
Otherwise, the variable is populated only with unrecognized MIME type
of the data. However, the preferred method for accessing the raw POST
data is php://input. $HTTP_RAW_POST_DATA is not available with
enctype="multipart/form-data".

My best guess is just add all the data as a ByteArrayBody or StringBody and just
use that as if you were reading from php://stdin

Here is an example of ByteArrayBody:

String testString="b=a&c=a&d=a&Send=Send";
reqEntity.addPart(new FormBodyPart("formVariables", new ByteArrayBody(testString.getBytes(), "application/x-www-form-urlencoded", "formVariables")));

And in PHP:

var_dump(file_get_contents($_FILES['formVariables']['tmp_name']));

You should get:

string(21) "b=a&c=a&d=a&Send=Send"

Edit: After some second thoughts I think it's better to just use one StringBody and put all the data in one post variable, then parse it from that, it skips writing the data to a file and deleting it after the request since the temp file is totally useless this will increase performance.
Here is an example:

String testString="b=a&c=a&d=a&Send=Send";
bodyPart=new FormBodyPart("rawData", new StringBody(testString));
reqEntity.addPart(bodyPart);

Then from PHP:

var_dump($_POST['rawData']);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文