473,761 Members | 10,057 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Posting multipart form-data to a web server

8 New Member
Hi,
I have a C++ routine(client-side) which uploads an xml file to a web server by making a socket connection and sending all the post request through that socket.
On the server side I have a cgi script which receives all the data and creates a file in the specified directory.
If I am uploading only the file all works well, however I want to send data of other fields too (field1, field2 ..etc), this fails the post request and even the file is not uploaded.
I think it has something to do with the Boundary Strings that need to be sent with each part of the form-data.
However I am unable to understand how to do that.
Greatly appreciate any help.
Here is my code snippet for preparing the post request for sending the form-data
Expand|Select|Wrap|Line Numbers
  1. int Send_to_DB_via_HTTP(char* Traveller_output_buffer, unsigned data_len, string fileName, string servIP, string url)
  2. {
  3.  
  4.      int sock;                          /*  Socket descriptor */
  5.         struct sockaddr_in echoServAddr;   /*  server address */
  6.         unsigned short echoServPort;       /*  server port */
  7.         char *echoString;                  /*  String to send to echo server */
  8.         char echoBuffer[RCVBUFSIZE];       /* Buffer for echo string */
  9.         unsigned int echoStringLen;        /* Length of string to echo */
  10.         int bytesRcvd, totalBytesRcvd;     /* Bytes read in single recv()
  11.                                                    and total bytes read */
  12.     int                         first_form_len=0;
  13.         int                         second_form_len=0;
  14.     int                hidden_data_len=0;
  15.     unsigned             count = 0;
  16.     int    count1 = 0;
  17.     int    count2 = 0;
  18.     char buf[2000];
  19.     int n;
  20.     const char *m_servIP;
  21.     const char *m_url;
  22.     m_servIP = servIP.c_str();
  23.     m_url = url.c_str();
  24.     echoServPort = 80;
  25.  
  26.      /*Create a reliable, stream socket using TCP */
  27.  
  28.     if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
  29.           cout << " socket () failed" << endl;
  30.  
  31.     /* Construct the server address structure */
  32.  
  33.     memset(&echoServAddr, 0, sizeof(echoServAddr));         /* Zero out structure */
  34.     echoServAddr.sin_family         = PF_INET;              /* Internet address family */
  35.     echoServAddr.sin_addr.s_addr = inet_addr(m_servIP);       /* Server IP address */
  36.     echoServAddr.sin_port           = htons(echoServPort); /* Server port */
  37.  
  38.     /* Establish the connection to the echo server */
  39.     int k;
  40.     k = connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr));
  41.  
  42.     if (k < 0)
  43.     {
  44.           cout<< "Error Connecting to " << servIP << endl;
  45.     return -1;
  46.     }
  47.     else
  48.      cout << "Connection Successfull to " << servIP << endl;
  49.  
  50.      //Start the form off with the boundary string
  51.     hidden_data_len += snprintf(
  52.             &Buffer3[hidden_data_len],
  53.             sizeof(Buffer3) - hidden_data_len,
  54.             "%s%s\r\n",
  55.             "--", BOUNDARY_STRING);
  56.     hidden_data_len += snprintf(
  57.                         &Buffer3[hidden_data_len],
  58.                         sizeof(Buffer3) - (hidden_data_len),
  59.                         "Content-Disposition: form-data;name=\"field1\"\r\n\r\n%s_auto_end\r\n",
  60.                         syssn_no );
  61.  
  62.  
  63.     //End of multi-part form
  64.     hidden_data_len += snprintf(
  65.                         &Buffer3[hidden_data_len],
  66.                         sizeof(Buffer3) - (hidden_data_len),
  67.                         "%s%s%s\r\n",
  68.                         "--",BOUNDARY_STRING,"--" );
  69.     first_form_len += snprintf(
  70.                         &buffer1[first_form_len],
  71.                         sizeof(buffer1) - first_form_len,
  72.                         "%s%s\r\n",
  73.                         "--",BOUNDARY_STRING );
  74.     //Some random filename - must end in .dat because web server checks
  75.     //This is the data portion of the form - the flat file will be sent in this section
  76.     first_form_len += snprintf(
  77.                         &buffer1[first_form_len],
  78.                         sizeof(buffer1) - first_form_len,
  79.                         "Content-Disposition: form-data; name=\"flat_file\"; filename=\"travellerdata.dat\"\r\n" );
  80.  
  81.     first_form_len += snprintf(
  82.                         &buffer1[first_form_len],
  83.                         sizeof(buffer1) - first_form_len,
  84.                         "Content-Type: text/plain\r\n\r\n" );
  85.  
  86.  
  87.     //Prepare the ending part of the form-data - this follows the flat file contents
  88.     //Start the form off with the boundary string
  89.     /*second_form_len += snprintf(
  90.                         &buffer1[first_form_len+second_form_len],
  91.                         sizeof(buffer1) - (first_form_len+second_form_len),
  92.                         "%s%s\r\n",
  93.                         "--",BOUNDARY_STRING );*/
  94.  
  95.  
  96.     // Put together the headers for HTTP POST
  97.     count = snprintf(
  98.                        &buffer[0],
  99.                        sizeof(buffer),
  100.                        "POST %s HTTP/1.1\r\n",
  101.                        m_url);
  102.  
  103.     count += snprintf(
  104.                         &buffer[count],
  105.                         sizeof(buffer) - count,
  106.                         "Accept-Language: en-us\r\n" );
  107.     count += snprintf(
  108.                         &buffer[count],
  109.                         sizeof(buffer) - count,
  110.                         "Content-Type: multipart/form-data; boundary=%s\r\n",
  111.                         BOUNDARY_STRING);
  112.  
  113.  
  114.     count += snprintf(
  115.                         &buffer[count],
  116.                         sizeof(buffer) - count,
  117.                         "User-Agent: Mozilla/3.01 (compatible)\r\n");
  118.     count += snprintf(
  119.                         &buffer[count],
  120.                         sizeof(buffer) - count,
  121.                         "Host: %s\r\n",
  122.                         m_servIP);
  123.  
  124.  
  125.     count += snprintf(
  126.                         &buffer[count],
  127.                         sizeof(buffer) - count,
  128.                         "Pragma: no-cache\r\n" );
  129.     count += snprintf(
  130.                         &buffer[count],
  131.                         sizeof(buffer) - count,
  132.                         "Content-Length: %d\r\n",
  133.                         data_len+first_form_len+second_form_len+hidden_data_len );
  134.     count += snprintf(
  135.                         &buffer[count],
  136.                         sizeof(buffer) - count,
  137.                         "\r\n" );
  138.     //cout << buffer << endl;
  139.    count1 += snprintf(
  140.             &buffer2[count1],
  141.             sizeof(buffer2) - count1,
  142.             "%s%s\r\n",
  143.                         "--",BOUNDARY_STRING);
  144.  
  145.    count1 += snprintf(
  146.             &buffer2[count1],
  147.             sizeof(buffer2) - count1,
  148.             "Content-Disposition: form-data; \"\r\n");
  149.    count1 += snprintf(
  150.             &buffer2[count1],
  151.             sizeof(buffer2) - count1,
  152.             "Content-Type: text/html\r\n");
  153.    count1 += snprintf(
  154.             &buffer2[count1],
  155.             sizeof(buffer2) - count1,
  156.             "Content-Length: %d\r\n", data_len);
  157.    count2 += snprintf(
  158.             &buffer3[count2],
  159.             sizeof(buffer3) - (count1+count2),
  160.             "%s%s%s\r\n",
  161.             "--",BOUNDARY_STRING, "--");
  162.  
  163.     string status;
  164.  
  165.     cout << "Sending Post Headers" << endl<< buffer << endl << "End Post Headers" << endl;
  166.  
  167.     //Send the "POST" header to the HTTP server.
  168.     if (send(sock, buffer, count, 0) == -1) {
  169.  
  170.         //status = perror("send");
  171.         cout << "Stats Worker: received socket error %d on header send\n" << endl;
  172.         return -1;
  173.     }
  174.  
  175.     cout << "Hidden Data" << endl<< Buffer3 << endl << "End Post Headers" << endl;
  176.     if (send(sock, Buffer3, hidden_data_len, 0) == -1) {
  177.  
  178.         //status = perror("send");
  179.         cout << "Stats Worker: received socket error %d on header send\n" << endl;
  180.         return -1;
  181.     }
  182.     cout << "Now Sending first part of the form data BUFFER1" << endl << buffer1 << endl<< "End First Part"<< endl;
  183.  
  184.  
  185.  
  186.     if (send(sock, buffer1, first_form_len, 0) == -1) {
  187.  
  188.         //status = CK_Get_last_error();
  189.         cout << "Stats Worker: received socket error on header send\n" << endl;
  190.         return -1;
  191.     }
  192.  
  193.     cout << "Now Sending file " << Traveller_output_buffer << endl;
  194.     //Now send the flat file
  195.     if (send(sock, Traveller_output_buffer, data_len, 0) == -1) {
  196.  
  197.         //status = CK_Get_last_error();
  198.  
  199.         cout << "Stats Worker: received socket error %d on message send\n" << endl;
  200.         return -1;
  201.     }
  202.     cout << "Sending ending boundary string " << endl << buffer3 << endl;
  203.     if (send(sock, buffer3, count2, 0) == -1) {
  204.  
  205.         //status = perror("send");
  206.         cout << "Stats Worker: received socket error %d on header send\n" << endl;
  207.         return -1;
  208.     }
  209.  
  210.     //Send the last part of the form data to the HTTP server.
  211.     /*if (send(sock, buffer1+first_form_len, second_form_len, 0) == -1) {
  212.  
  213.         //status = CK_Get_last_error();
  214.         cout << "Stats Worker: received socket error %d on header send\n" << endl;
  215.         return -1;
  216.     }*/
  217.  
  218.     //Receive server response
  219.  
  220.     n = recv(sock, buf, 2000, 0);
  221.     //cout << "Server Response is " << endl << buf << endl;
  222.     if(n < 0)
  223.     {
  224.         cout << "Upload Failed" << endl;
  225.         return -1;
  226.     }
  227.  
  228.     // Make sure this is a HTTP header
  229.     if (!strstr(buf, "HTTP")) {
  230.  
  231.         cout << "Stats Worker: response doesn't contain HTTP\n";
  232.         return -1;
  233.     }
  234.  
  235.     if (n < 0) {
  236.  
  237.         cout << "Stats Worker: response status is " << n;
  238.         return -1;
  239.     }
  240.  
  241.         // while (n > 0) {
  242.      //printf(buf);
  243.             if(!strstr(buf, Successful_Upload))
  244.          {
  245.         cout << "Traveller Upload Failed. Server Responded " << buf;
  246.         return -1;
  247.         }
  248.          else
  249.         {
  250.          cout << "Traveller Upload Successfull. \n Server Response is \n" << buf;
  251.          //return 0;
  252.         }
  253.             //n = recv(sock, buf, 10480, 0);
  254.          //}
  255.  //remove("newtravellerdata.dat");
  256. //close(sock);
  257. }
  258.  
If required I can upload the server side cgi too.

Thanks,
Mohit
Sep 25 '08 #1
1 9790
starter08
8 New Member
Hi,
Can anybody help me out.
This is the whole output that I am trying to send through a post request
Expand|Select|Wrap|Line Numbers
  1. POST http://192.168.2.5/upload.cgi HTTP/1.1
  2. Accept-Language: en-us
  3. Content-Type: multipart/form-data; boundary=---------------------------7d2b119100532
  4. User-Agent: Mozilla/3.01 (compatible)
  5. Host: 192.168.2.5
  6. Pragma: no-cache
  7. Content-Length: 717
  8.  
  9. -----------------------------7d2b119100532
  10. Content-Disposition: form-data; name="field1"
  11.  
  12. 5107115015_auto_end
  13. -----------------------------7d2b119100532
  14. Content-Disposition: form-data; name="flat_file"; filename="travellerdata.dat"
  15. Content-Type: text/plain
  16.  
  17. <SYSSN>5107115015</SYSSN>
  18. <HDD slot="0">
  19.     <serial>DA40P7C003P5</serial>
  20.     <model>MAW3300NC</model>
  21.     <firmware>0104</firmware>
  22. </HDD>
  23. <network>
  24.     <adapter slot="1">
  25.         <interface slot="1">
  26.             <mac>00:E0:81:4B:8F:FD</mac>
  27.         </interface>
  28.     </adapter>
  29. </network>
  30. <BIOS>
  31.     <revision></revision>
  32.     <date>06/23/06</date>
  33. </BIOS>
  34. <CPU_count>4</CPU_count>
  35. <CPU slot="0">
  36.     <serial>00020F120000000000000000</serial>
  37. </CPU>
  38. -----------------------------7d2b119100532--
  39.  
however I receive the following response back from the server

Server Response is
HTTP/1.1 200 OK
Date: Fri, 26 Sep 2008 05:13:55 GMT
Server: Apache/2.2.3 (Debian) PHP/5.2.0-8+etch10
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

f3
<h1>Software error:</h1>
<pre>Malforme d multipart POST
</pre>
<p>
For help, please send mail to the webmaster (<a href="mailto:we bmaster@localho st">webmaster@l ocalhost</a>), giving this error message
and the time and date of the error.

</p>
Sep 26 '08 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

34
4473
by: Niels Berkers | last post by:
Hi, i'd like to host my web pages using multiparts to reduce the number of hits on the server. i know this isn't a real PHP subject, but i'll try it anyway. i've been searching the web for solutions and examples with no succes. does anybody know a good starting point hints / tips are also welcome Regards
6
2944
by: LRW | last post by:
Because I've had recipients of our newsletter tell us they can't (or won't) receive HTML e-mail, I found out how to make an e-mail that sends both HTML and a plaintext version in a multipart message. Problem is, while the HTML version shows up fine in HTML enabled clients like Outlook, in plaintext clients it either shows nothing in the body or just an attachment link to the message source code. I've tried different encodings and bits...
2
3203
by: Damien | last post by:
Hi to all, After hours of attempts and "googling", I'm still pulling my hair off my head when I try to send multipart html emails. It "works" on PCs with Outlook when I juste send a single "related" mail: one part for the HTML body, and several for the images. However, the images do not show on a Mac. I also wanted to have an "alternate", plain text message. I've tried the method described by Zend and PHPBuilder, but no luck...
4
2990
by: Hunter Peress | last post by:
I have been unable to write a script that can do (and receieve) a multipart form upload. Also, it seems that there really are differences between python's implementation and else's. Can someone please prove me wrong with a script that works with itself AND with example 18-2 from php: http://www.php.net/manual/en/features.file-upload.php __________________________________
0
1900
by: Travis Pupkin | last post by:
Hi, I have a form that triggers the sending of an e-mail via CDOSYS. I'd like to make this a nice HTML-formatted multipart message, but for some reason the text version is coming through blank. Originally I thought I had read that CDO has an automatic text converter that will turn the HTML code into a plain TEXT message, but when that didn't work (and I couldn't find anything further about it), I added a custom text line like this:
2
5045
by: Der tolle Emil | last post by:
Hi! I wrote a little function to send emails which works quite well. I already managed to send attachments correctly (also more than 1 per email) but I am not able to send a HTML mail containing a text only block for non-HTML clients. I will not post the PHP code as I think it is irrelevant, the error lies within the mail header and/or body, so here is the mail I do want to send: FROM: me <foo@bar.com>
2
6309
by: madmak | last post by:
Hi, I am a noob with PHP and need some asistance regarding PHP and lotus notes. I am trying to create a multipart message in PHP to send mail via lotus notes. Here is the code snippet. <?php ---some code here -- $session_notes = new COM("Lotus.NotesSession"); $session_notes->Initialize("<password>");
6
10569
by: fnoppie | last post by:
Hi, I am near to desperation as I have a million things to get a solution for my problem. I have to post a multipart message to a url that consists of a xml file and an binary file (pdf). Seperately the posting words fine but when I want to create one multipart message with both then things go wrong. The binary file is converted and of datatype byte() The xml file is just a string.
0
1506
by: pezkel | last post by:
Hi, For the last two weeks I have been looking for a solid way to create an asp page that can upload a binary file and an xml file in a multipart message to a third party website. I am on the verge of giving (and cracking) up so I would appreciate any pointers. I have used: http://www.motobit.com/tips/detpg_uploadvbsie/ and end up with the problem that I have a byte array for the binary file and a string for the xml. I have tried...
4
2885
by: ceh | last post by:
Hi, on windows xp I'm using xampp v 1.6.4 I'm trying to send mail. The mail always sends, but the multipart sections are broken. Essentially, I want to send an html email that has a link it, like http://www.google.com so the reader can click on the link. When I get the email, the body is empty.
0
9521
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10107
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9900
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9765
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8768
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5214
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3863
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3442
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.