How does the php server obtain the json data of multipart/form-datapost?

Source: Internet
Author: User
Tags php server
The php server obtains the json data client of multipartform-datapost by using java post a multipart/form-data request, which contains an array of json parameters and an uploaded file.
On the php Server, how does one parse/obtain json data?


Reply to discussion (solution)

The following is the java client code
Public void doPost (){
Log. d (TAG, "====== doHttpConnectionPost ");

HttpURLConnection conn = null;
DataOutputStream dos = null;
InputStream in = null;
Try {
StringBuilder paramStr = new StringBuilder ("");
Iterator I = mParam. keys ();
While (I. hasNext ()){
String key = I. next ();
Log. d (TAG, "key:" + key + ", value:" + mParam. getString (key ));
If (! (KEY_LOGFILE.equals (key ))){
If (paramStr. length ()> 0 ){
ParamStr. append ("&");
}
ParamStr. append (key );
ParamStr. append ("= ");
Try {
ParamStr. append (URLEncoder. encode (String. valueOf (mParam. getString (key), "UTF-8 "));
} Catch (UnsupportedEncodingException e ){
ParamStr. append (mParam. getString (key ));
}
}
}

If (mUrl. charAt (mUrl. length ()-1 )! = '? '){
MUrl = mUrl + "? ";
}
MUrl = mUrl + paramStr;

Log. d (TAG, "==== mUrl:" + mUrl );
URL url = new URL (mUrl );

Conn = (HttpURLConnection) url. openConnection ();
Conn. setReadTimeout (HTTP_PARAM_TIMEOUT );
Conn. setConnectTimeout (HTTP_PARAM_TIMEOUT );
Conn. setDoInput (true );
Conn. setDoOutput (true );
Conn. setRequestMethod ("POST ");
Conn. setRequestProperty ("Charset", CHARSET );
Conn. setRequestProperty ("connection", "keep-alive ");
Conn. setRequestProperty ("Content-Type", multipart/form-data + "; boundary =" + BOUNDARY );

Dos = new DataOutputStream (conn. getOutputStream ());
Log. d (TAG, "==== after open conn. getoutputstream ");

I = mParam. keys ();
Map Files = new HashMap ();
While (I. hasNext ()){
String key = I. next ();
If (KEY_LOGFILE.equals (key ))){
Log. d (TAG, "key:" + key + ", value:" + mParam. getString (key ));
If (! TextUtils. isEmpty (mParam. getString (key ))){
Files. put (key, new File (mParam. getString (key )));
}
}
}

For (Map. Entry File: files. entrySet ()){
If (file. getValue ()! = Null & file. getValue (). exists ()){
StringBuilder sb = new StringBuilder ();
Sb. append (PREFIX );
Sb. append (BOUNDARY );
Sb. append (LINEND );

Sb. append ("Content-Disposition: form-data; name = \" "+ file. getKey ()
+ "\"; Filename = \ "" + file. getValue (). getName () + "\" "+ LINEND );
Sb. append ("Content-Type: application/octet-stream; charset =" + CHARSET + LINEND );
Sb. append ("Content-Transfer-Encoding: 8bit" + LINEND );
Sb. append (LINEND );
Log. d (TAG, sb. toString ());

Dos. write (sb. toString (). getBytes ());
InputStream is = new FileInputStream (file. getValue ());
Log. d (TAG, "filevalue =" + file. getValue ());
Byte [] bytes = new byte [1, 1024];
Int len = 0;
While (len = is. read (bytes ))! =-1 ){
Dos. write (bytes, 0, len );
Log. d (TAG, "in read file" + len );
}
Is. close ();
Dos. write (LINEND. getBytes ());
}
}
Byte [] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND). getBytes ();
Dos. write (end_data );
Dos. flush ();

Int res = conn. getResponseCode ();
Log. d (TAG, "res =" + res );
If (res = 200 ){
In = conn. getInputStream ();
Int ch;
StringBuilder sb2 = new StringBuilder ();
While (ch = in. read ())! =-1)
{
Sb2.append (char) ch );
}
Log. d (TAG, "response entity string:" + sb2 );
MResponse = new JSONObject (sb2.toString ());
} Else {
Log. d (TAG, conn. getResponseCode () + conn. getResponseMessage ());
In = conn. getErrorStream ();
}
} Catch (IOException e ){
E. printStackTrace ();
} Catch (JSONException e ){
E. printStackTrace ();
} Finally {
Try {
If (in! = Null ){
In. close ();
}
If (dos! = Null ){
Dos. close ();
}
If (conn! = Null ){
Conn. disconnect ();
}
} Catch (IOException e ){
E. printStackTrace ();
}
}
}

File_put_contents('test.txt ', print_r ($ _ POST, 1 ));
See what's in test.txt.

Json data cannot be obtained using _ POST.

All conclusions are taken after investigation and research!

File_put_contents('test.txt ', print_r ($ _ POST, 1 ));
Output to the test.txt file is empty.

Can someone help me with this problem?

No? You just
File_put_contents('test.txt ', file_get_contents ('php: // input '));
See what's in test.txt.

Your client is Java. who will copy a test for you?
You are using the post method, but $ _ POST has no value. Apparently it's a problem with your client!

Isn't it a normal application to upload a few pieces of data simultaneously?

This multipart/form-data has a relationship.
Json data cannot be obtained using $ _ POST.
This is not a client issue, boss! Other non-php servers with the same java code are easy to use.
Have you done this Upload?

This is a simple question for php users who have some experience. please help me.
The uploaded file can be obtained normally, that is, it does not know how to obtain json data.

Let you
File_put_contents('test.txt ', file_get_contents ('php: // input '));
See what's in test.txt.
Have you done it?

Boss, I did. there's nothing in it. didn't I reply?

'Php: // input' cannot obtain post data in multipart/form-data mode. do you know?

You only reply to file_put_contents('test.txt ', print_r ($ _ POST, 1); no content
File_put_contents('test.txt ', file_get_contents ('php: // input'); no content

Php: // The input is not parsed by php (or the remaining input stream after php parsing)

If php: // input has no content, it must have been parsed by php.
You can check whether $ _ FILES has a value. it is very likely that your data is processed as an uploaded file.
Do not always think of the special characteristics of json. for network transmission, it is just a string. As long as you send the message, it must be in the data stream.
Multipart/form-data is a special case of application/x-www-form-urlencoded
You can also consider it an extension of application/x-www-form-urlencoded.
To upload files using the http protocol, you must have a multipart/form-data declaration and organize the data as agreed.

As for whether I have uploaded files, you can find the methods for uploading files that I participated in a few years ago in the essence area.
It is because it is completely written in accordance with the specifications, and there is indeed no failure experience.

File_put_contents('test.txt ', file_get_contents ('php: // input '));
There is no content in the file ;-(

File_put_contents('test.txt ', print_r ($ _ FILES, 1 ));
Should there be content?

File_put_contents('test.txt ', print_r ($ _ FILES, 1 ));
The output is as follows:

Array
(
[LogFile] => Array
(
[Name] => log.zip
[Type] => application/octet-stream
[Tmp_name] =>/var/www/php7Ax336
[Error] => 0
[Size] = & gt; 28571
)

)

Well, this is why the attached data is not named.
Php ignores the data in the "name =" "section when parsing the post data.

Therefore, we used curl to perform a test.

$ File = realpath('0.txt '); $ fields = array ('F' => '@'. $ file, ''=> 'abcd', // you cannot receive it without a name. Otherwise, you can receive it.); $ ch = curl_init (); curl_setopt ($ ch, CURLOPT_URL, "http: // localhost/ajax_server.php? Id = 1 "); curl_setopt ($ ch, CURLOPT_POST, 1); curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ fields); curl_exec ($ ch); curl_close ($ ch );
However, the data is completely transmitted
-------------------------- 6e77d33195b450f3content-disposition: form-data; name = "f"; filename = "D: \ AMP \ web \ 0.txt" Content-Type: application/octet-stream this is a test ------------------------ 6e77d33195b424f3content-disposition: form-data; name = "" abcd ------------------------ 6e77d33195b%f3 --

Therefore, it is best to negotiate with the client developers to name each data item.
Of course, you can also use php to solve this problem, that is, add
Enable_post_data_reading = Off
This prevents php from parsing post data.
The input stream can be obtained by php: // input.
Then you can classify and save the data you read. you must be more diligent than php and cannot ignore data items without names.

Note: Because you have prevented php from parsing the post data, $ _ POST and $ _ FILES are invalid! Switch note during application

Therefore, it is best to negotiate with the client developers to name each data item.
What is the meaning of a name for each data item? My post data:
Http://api.hdtv.com/save? ModelName = % E8 % AE % BE % E7 % BD % AE & type = S60 & contact = 777720 & description = & version = V320R470C096B07166T & versionName = 3.0.096T & model = S60 & ui = 3.0 & hwVersion = H5001 & mac = be60ebe15a7c

Is the solution only to modify php. ini?

I #17 lower part 7th rows
Content-Disposition: form-data; name = ""
Name is an empty string, that is, there is no name

Do I have to call a name when I look for someone? Who will step on you?


What does that connection mean? Nothing is displayed

Hello,

My name has a name? Name‑log.zip

The link is the url of the post data and has a name.

How can this problem be solved?

Didn't you say that it contains an array of json parameters and an uploaded file?
Print $ _ FILES available
[LogFile] => Array
(
[Name] => log.zip
This file has a name, indicating that the file is uploaded correctly.
Print $ _ POST is empty (#5)
The json data is not received

Your connection is not displayed. I wonder if it is correct. It looks at the source code (not very careful) and does not see any upload or submission.

Besides, it is a js operation page. what is the relationship with Java?

My code is uploaded by android java on the mobile phone,
What do you mean by js?
Is there any way? Hero

This java code can be used with other servers,
I want to use php on the server.
Could you help me?

The cause of the problem is found.
Http://api.hdtv.com/save? ModelName = % E8 % AE % BE % E7 % BD % AE & type = S60 & contact = 777720 & description = & version = V320R470C096B07166T & versionName = 3.0.096T & model = S60 & ui = 3.0 & hwVersion = H5001 & mac = be60ebe15a7c
The parameters in this url must be obtained using _ GET,

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.