use*_*126 5 c++ upload image poco-libraries
我正在尝试将图像上传到远程Web服务器.我使用过HTMLForm和FilePartSource.我能够成功将图像上传到本地服务器(即loclhost),但是当我尝试将其上传到远程服务器时,从远程Web服务器收到的响应是"411 Length Required".我试图设置request.setContentLength(sizeofimagefile)但仍然是同样的问题.任何人都可以指导我什么是问题或.这是我的代码.
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();
Run Code Online (Sandbox Code Playgroud)
提前致谢
std::ostream& oustr = session.sendRequest(post_req);
htmlform.write(oustr);
Run Code Online (Sandbox Code Playgroud)
您的代码无法将表单数据分配到请求对象中。因此,当您调用 session.sendRequest 时,会向服务器发送一个空请求。要将 HTMLForm 正确转换为 HTTPRequest,您必须这样写 -
htmlform.write(session.sendRequest(post_req));
对我有用的图像上传代码是 -
Run Code Online (Sandbox Code Playgroud)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);
相应的上传服务器使用标准的 PHP 代码上传 HTML 表单文件。
如果您可以将文件上传到本地服务器,但不能上传到远程服务器,首先您应该检查您的远程 Apache/PHP 是否有上传限制。在远程服务器中尝试 phpinfo()。
http://www.cyberciti.biz/faq/linux-unix-apache-increase-php-upload-limit/
如果没有,你应该修改你的代码......
来自 Poco 文档,网址为: http: //www.appinf.com/docs/poco/Poco.Net.HTMLForm.html
HTML 表单:
HTMLForm( const HTTPRequest & request, std::istream & requestBody);
根据给定的 HTTP 请求创建 HTMLForm。上传的文件会被默默丢弃。
并使用这个构造函数:
HTML 表单:
HTMLForm( const HTTPRequest & request, std::istream & requestBody, PartHandler & handler);
根据给定的 HTTP 请求创建 HTMLForm。上传的文件将传递给给定的 PartHandler。
在您的示例中,您正在应用什么构造函数?
另一方面,
添加部分:
void addPart( const std::string & name, PartSource * pSource ); 将部分/附件(文件上传)添加到表单。表单取得 PartSource 的所有权,并在不再需要时将其删除。仅当表单的编码设置为“multipart/form-data”时才会发送该部分
尝试将“multipart/form-data”与 addPart 和 HTMLForm 的第二个构造函数一起使用。
如果不起作用,请尝试使用 Wireshark 等网络嗅探器来检查您发送的内容。
检查您的请求的 Content-Length 标头是否具有 sizeof(您的图像) + sizeof("aaaaaa" 和 "cccccc" params)。或者尝试使用 GET 方法而不是 POST 发送表单。
让我知道它是否有效。
问候