Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POCO : How to upload image to webser using poco in c++

I am trying to upload an image to remote web server. I have used HTMLForm and FilePartSource. I am able to successfully upload image to local sever (i.e. loclhost) but when i try to upload it in remote server, the response received from remote web server is "411 Length Required ". I tried to set request.setContentLength(sizeofimagefile) but still same issue. Can anyone guide me on what is the issue or . Here is my code.

    HTMLForm htmlform;
htmlform.set("aaaaaa", "bbbbbbb");
htmlform.set("cccccc", "ddddddd");
htmlform.setEncoding(HTMLForm::ENCODING_MULTIPART);

PartSource * pFileSrc = new FilePartSource("filename", "application/octet-stream");

std::istream& mystream = pFileSrc->stream();
mystream.seekg(0, std::ios::end);
int uiLength = mystream.tellg();

    htmlform.addPart("file", pFileSrc);

URI uri("yyy");

    HTTPClientSession session(uri.getHost(), uri.getPort());        
HTTPRequest post_req(Poco::Net::HTTPRequest::HTTP_POST,"xxx",HTTPMessage::HTTP_1_1);        
post_req.setKeepAlive(true);
htmlform.prepareSubmit(post_req);


std::ostream& oustr = session.sendRequest(post_req);
htmlform.write(oustr);

HTTPResponse res;
std::istream& rs = session.receiveResponse(res);

std::cerr << rs.rdbuf(); 

Thanks in advance

like image 233
user1918126 Avatar asked Dec 20 '12 08:12

user1918126


1 Answers

std::ostream& oustr = session.sendRequest(post_req);
htmlform.write(oustr);

Your code is not able to assign form data into the request object. So when you call session.sendRequest, an empty request is sent to the server. To do a proper conversion of HTMLForm to HTTPRequest, you must write like this -

htmlform.write(session.sendRequest(post_req));

The image upload code which is working for me is -

    HTTPRequest request(HTTPRequest::HTTP_POST, "/fileupload/upload_file.php",    HTTPMessage::HTTP_1_1);
    HTMLForm form;
    form.setEncoding(HTMLForm::ENCODING_MULTIPART);
    form.set("entry1", "value1");
    form.set("entry2", "value2");
    form.addPart("file", new FilePartSource("/home/abc/Pictures/sample.png"));
    form.prepareSubmit(request);

    HTTPClientSession *httpSession = new HTTPClientSession("localhost");
    httpSession->setTimeout(Poco::Timespan(20, 0));
    form.write(httpSession->sendRequest(request));        

    Poco::Net::HTTPResponse res;
    std::istream &is = httpSession->receiveResponse(res);
    Poco::StreamCopier::copyStream(is, std::cout);

The corresponding upload server is using standard PHP code for uploading HTML form files.

like image 90
Gaurav Raj Avatar answered Nov 05 '22 06:11

Gaurav Raj