How PHP Server-side obtains JSON data for Multipart/form-data Post

Source: Internet
Author: User
Tags php server
The client is a multipart/form-data request with a Java post that contains an array of JSON parameters, and an uploaded file.
How do I parse/get JSON data on the PHP server side?


Reply to discussion (solution)

Here 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[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 is not available with _post.

All the conclusions are after the investigation!

File_put_contents (' Test.txt ', Print_r ($_post, 1));
The output to the Test.txt file is empty.

Have a master to help look at this problem?

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

Your client is Java, who will facsimile a test for you?
You said it was post, but $_post is not worth it. Obviously the problem with your client!

Uploading a file while transmitting several data is not a very normal application?

This multipart/form-data is related.
You cannot use $_post to fetch JSON data.
This is not the client's problem, Boss! The same Java code other non-PHP servers are handy.
Have you ever done this way of uploading?

This question for a little PHP experience students should be very simple, please help ha.
Now the uploaded files can be obtained normally, just don't know how to get the JSON data.

I let you
File_put_contents (' Test.txt ', file_get_contents (' php://input '));
See what's in Test.txt.
Did you do it?

Boss, did it, there's nothing in it, I'm not replying?

' Php://input ' gets no data for Multipart/form-data mode post, don't you know?

You only reply to say File_put_contents (' Test.txt ', Print_r ($_post, 1)); No content
And did not say File_put_contents (' Test.txt ', file_get_contents (' php://input ')); No content

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

If Php://input also has no content, it must have been parsed by PHP
You can see if the $_files has a value, and your data is likely to be treated as an upload file.
Do not always think that JSON is special, for network transmission, it is just a string. As long as you send it, it must be in the data stream.
Multipart/form-data is a special case of application/x-www-form-urlencoded.
You can also be seen as an extension of application/x-www-form-urlencoded
If you want to upload a file using the HTTP protocol, you must have a Multipart/form-data statement and organize the data in the way that he agreed.

As to whether or not I have uploaded files, you can find a discussion on the various methods of uploading files that I participated in prior years in the elite area.
Just because it was written exactly as it was, there was no experience of failure.

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

File_put_contents (' Test.txt ', Print_r ($_files, 1));
There's always something to do, right?

File_put_contents (' Test.txt ', Print_r ($_files, 1));
Printed out Is this:

Array
(
[LogFile] = = Array
(
[Name] = Log.zip
[Type] = Application/octet-stream
[Tmp_name] =/var/www/php7ax336
[ERROR] = 0
[Size] = 28571
)

)

Well, this is still the reason why the appended data is not named
When PHP parses the post-mode data, it ignores the data in the section name= ""

I did a test with curl for this.

$file = Realpath (' 0.txt '); $fields = Array (' f ' = ' @ ') $file, ' = ' and ' ABCD ',//No Name is not received, otherwise it can be received); $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);  
But the data is intact.
--------------------------6e77d33195b440f3content-disposition:form-data; Name= "F"; Filename= "D:\\amp\\web\\0.txt" content-type:application/ Octet-stream This is a test--------------------------6e77d33195b440f3content-disposition:form-data; Name= "" ABCD--------------------------6e77d33195b440f3--

So it's best to negotiate with the client's developers and give each data item a name.
Of course, you can also use PHP to solve this problem, that is, in the php.ini to add
enable_post_data_reading = Off
This prevents PHP from parsing the post-mode data action
The input stream can be php://input taken to the
Then you sort of read the data to save, you must be more diligent than PHP, it is impossible to ignore the name of the data items

Note: Because you blocked PHP parsing the post data, so $_post, $_files are not valid! Pay attention when applying

So it's best to negotiate with the client's developers to give each data item a name.
What does it mean to have a name for every data item? Data for my post:
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 solution can only be modified php.ini?

I #17 the lower 7th line.
Content-disposition:form-data; Name= ""
Name is an empty string, just no Name

Don't you want to call a name for someone? Hey, who's stepping on you?


What do you mean by that connection? Nothing's going to show.

Hello, Warrior.

My name is named? Name=log.zip

That link is the URL to the post data, and it has a name.

How to solve this problem, please, hero?

You're not saying: Contains an array of JSON parameters, and an uploaded file?
Print $_files have
[LogFile] = = Array
(
[Name] = Log.zip
This is a name, it means the file upload is correct.
Print $_post is empty (#5)
Indicates that the JSON data was not received

You that connection, one is not any display, do not know whether it is correct. But look at the source (not very carefully), nor see the upload or submit

And that is the JS operation of the page, what is the relationship with Java?

My code is the Android Java upload on the phone,
What do you mean by JS?
Is there any way to do that? Warrior

This Java code is not a problem with other server mates,
I now want to use PHP to receive it on the server side.
Ask the Warrior, master help Ah

This problem is finding a reason.
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 are to be obtained by _get,

  • 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.