Can be used in two ways:
1. $data is null (default): $filename is treated as the name if a local file which
will be read and sent. Will try to guess the content type using mime_content_type().
2. $data is set - $filename is sent as the file name, but $data is sent as the file
contents and no file is read from the file system. In this case, you need to
manually set the Content-Type ($ctype) or it will default to
application/octet-stream.
public setFileUpload ( string $filename, string $formname, string $data = null, string $ctype = null ) : Zend_Http_Client | ||
$filename | string | Name of file to upload, or name to save as |
$formname | string | Name of form element to send as |
$data | string | Data to send (if null, $filename is read and sent) |
$ctype | string | Content type to use (if $data is set and $ctype is null, will be application/octet-stream) |
return | Zend_Http_Client |
/** * Add an media file to mobypicture. * * @param string $filepath * @param string $title * @param string $description * @param string $format * @param array $options * @throws Zend_Http_Client_Exception if HTTP request fails or times out * @throws HausDesign_Service_Mobypicture_Exception If username is not set * @throws HausDesign_Service_Mobypicture_Exception If file can't read. * @throws HausDesign_Service_Mobypicture_Exception If file is larger then 16M. * @return mixed */ public function postMedia($filepath, $title, $description = '', $format = self::FORMAT_XML, $options = array()) { if (null == $this->_username || null == $this->_password) { throw new HausDesign_Service_Mobypicture_Exception('Username and password must be set.'); } if (!is_readable($filepath)) { throw new HausDesign_Service_Mobypicture_Exception('File can\'t be read.'); } if (filesize($filepath) > 16777216) { throw new HausDesign_Service_Mobypicture_Exception('File can\'t be larger then 16M.'); } if (strlen($title) > self::MAX_LENGTH_TITLE) { $title = substr($title, 0, self::MAX_LENGTH_TITLE); } if (strlen($description) > self::MAX_LENGTH_DESCRIPTION) { $title = substr($title, 0, self::MAX_LENGTH_DESCRIPTION); } $options['t'] = $title; if ($description) { $options['d'] = $description; } $this->_localHttpClient->resetParameters(); $this->_localHttpClient->setUri(self::MOBYPICTURE_API); $this->_localHttpClient->setParameterPost('action', 'postMediaUrl'); $this->_localHttpClient->setFileUpload($filepath, 'i'); $this->_localHttpClient->setParameterPost('u', $this->_username); $this->_localHttpClient->setParameterPost('p', $this->_password); $this->_localHttpClient->setParameterPost('k', $this->_apiKey); $this->_localHttpClient->setParameterPost('format', $format); $this->_localHttpClient->setConfig(array('timeout' => 30)); foreach ($options as $option => $value) { $this->_localHttpClient->setParameterPost($option, $value); } return $this->_parseContent($this->_localHttpClient->request('GET')->getBody(), $format); }
public function testUploadNameWithSpecialChars() { $this->client->setUri($this->baseuri . 'testUploads.php'); $rawdata = file_get_contents(__FILE__); $this->client->setFileUpload('/some strage/path%/with[!@#$&]/myfile.txt', 'uploadfile', $rawdata, 'text/plain'); $res = $this->client->request('POST'); $body = 'uploadfile myfile.txt text/plain ' . strlen($rawdata) . "\n"; $this->assertEquals($body, $res->getBody(), 'Response body does not include expected upload parameters'); }
/** * @group ZF-10664 * * Test that you can post a file using a preset * Zend_Http_Client that has a file to post, * by calling $restClient->setNoReset() prior to issuing the * restPost() call. */ public function testCanPostFileInPresetHttpClient() { $client = new Zend_Rest_Client('http://framework.zend.com'); $httpClient = new Zend_Http_Client(); $text = 'this is some plain text'; $httpClient->setFileUpload('some_text.txt', 'upload', $text, 'text/plain'); $client->setHttpClient($httpClient); $client->setNoReset(); $client->restPost('/file'); $request = $httpClient->getLastRequest(); $this->assertTrue(strpos($request, $text) !== false, 'The file is not in the request'); }
function mts($message, $phones, $config) { $ok = false; $client = new Zend_Http_Client('https://corpsms.ru/api/http/sendsms'); $y = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getOption('sms'); $y = $y['mts']; $client->setAuth($y['login'], $y['password']); $client->setParameterPost(array('msg' => $message)); $client->setFileUpload('', 'phones', implode("\n", $phones), 'text/plain'); $response = $client->request('POST'); return $response->getStatus() == 200 && stripos($response->getBody(), 'error') == false; }
/** * Test that one can upload multiple files with the same form name, as an * array * * @link http://framework.zend.com/issues/browse/ZF-5744 */ public function testMutipleFilesWithSameFormNameZF5744() { $rawData = 'Some test raw data here...'; $this->client->setUri($this->baseuri . 'testUploads.php'); $files = array('file1.txt', 'file2.txt', 'someotherfile.foo'); $expectedBody = ''; foreach ($files as $filename) { $this->client->setFileUpload($filename, 'uploadfile[]', $rawData, 'text/plain'); $expectedBody .= "uploadfile {$filename} text/plain " . strlen($rawData) . "\n"; } $res = $this->client->request('POST'); $this->assertEquals($expectedBody, $res->getBody(), 'Response body does not include expected upload parameters'); }
/** * * @param string $url * @param array $param * @param string $method * @return string */ protected function _request($url, $param = array(), $method = Zend_Http_Client::POST) { if ($this->_client === null) { $config = array('useragent' => 'Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/44.0', 'encodecookies' => false, 'timeout' => 180); $this->_client = new Zend_Http_Client($url, $config); $this->_client->setCookieJar(); } $this->_client->resetParameters()->setUri($url); if (count($param['post']) > 0) { foreach ($param['post'] as $name => $value) { $this->_client->setParameterPost($name, $value); } } if (count($param['get']) > 0) { foreach ($param['get'] as $name => $value) { $this->_client->setParameterPost($name, $value); } } if (count($param['file']) > 0) { foreach ($param['file'] as $name => $value) { $this->_client->setFileUpload($value, $name); } } if (count($param['cookie']) > 0) { foreach ($param['cookie'] as $name => $value) { $this->_client->setCookie($name, $value); } } if (count($this->_cookies) > 0) { foreach ($this->_cookies as $cookie) { $this->_client->setCookie($cookie); } } $response = $this->_client->request($method); $this->_cookies = $this->_client->getCookieJar()->getAllCookies(); return $response->getBody(); }
/** * @group ZF-10664 * * Test that you can post a file using a preset * Zend_Http_Client that has a file to post, * by calling $restClient->setNoReset() prior to issuing the * restPost() call. */ public function testCanPostFileInPresetHttpClient() { if (!defined('TESTS_ZEND_REST_ONLINE_ENABLED') || !constant('TESTS_ZEND_REST_ONLINE_ENABLED')) { $this->markTestSkipped('Define TESTS_ZEND_REST_ONLINE_ENABLED to test Zend_Rest_ClientTest online.'); } $client = new Zend_Rest_Client('http://framework.zend.com'); $httpClient = new Zend_Http_Client(); $text = 'this is some plain text'; $httpClient->setFileUpload('some_text.txt', 'upload', $text, 'text/plain'); $client->setHttpClient($httpClient); $client->setNoReset(); $client->restPost('/file'); $request = $httpClient->getLastRequest(); $this->assertTrue(strpos($request, $text) !== false, 'The file is not in the request'); }
/** * Makes a POST-request to the Visual Search Database REST-API * @param string $url the name of the php-file which handles a specific REST-API request. * @param array $config the config for Zend_Http_Client * @param array $params post parameter (associative array which maps key to value) * @param string $localFile full local path to file to be uploaded * @param string $fileUploadFormName form name that will be used when uploading a file * @return Zend_Http_Response POST request response from visual CVS API */ function doPost($url, $config, $params, $localFile = NULL, $fileUploadFormName = NULL) { try { $client = new Zend_Http_Client("https://my.metaio.com/REST/VisualSearch/" . $url, $config); $client->setMethod(Zend_Http_Client::POST); $client->setParameterPost($params); if ($localFile) { // Upload item to database $client->setFileUpload($localFile, $fileUploadFormName); } $response = $client->request(); } catch (Exception $e) { $response = new Zend_Http_Response('Client side exception', array(), "", '1.1', PHP_EOL . 'Exception: ' . $e->getMessage() . PHP_EOL); } return $response; }
/** * @group ZF-4236 */ public function testClientBodyRetainsFieldOrdering() { $this->_client->setAdapter('Zend_Http_Client_Adapter_Test'); $this->_client->setUri('http://example.com'); $this->_client->setParameterPost('testFirst', 'foo'); $this->_client->setFileUpload('testFile.name', 'testFile', 'TESTDATA12345', 'text/plain'); $this->_client->setParameterPost('testLast', 'bar'); $this->_client->request('POST'); $expectedLines = file(dirname(__FILE__) . '/_files/ZF4236-clientbodyretainsfieldordering.txt'); $gotLines = explode("\n", trim($this->_client->getLastRequest())); $this->assertEquals(count($expectedLines), count($gotLines)); while (($expected = array_shift($expectedLines)) && ($got = array_shift($gotLines))) { $expected = trim($expected); $got = trim($got); $this->assertRegExp("/^{$expected}\$/", $got); } }
/** * Sends an image to the Pixlr server, receiving back the image ID as the * response parameter, which is then forwarded to the browser * * This method is used as a means to work around the issue where images are stored * on servers that are behind firewalls, in which case pixlr's servers are unable to * retrieve the content directly, so it must be pushed to pixlr. * * This method is still relatively secure in that the image ID returned is only known to * us and pixlr - it is a unique key, effectively a one time password. * * @param HTTPRequest $request */ public function sendimage($request) { if (!isset($request['ID'])) { throw new Exception("Invalid image ID"); } $file = DataObject::get_by_id('Image', (int) $request['ID']); if ($file && $file->ID) { $client = new Zend_Http_Client($this->config()->pixlr_upload_uri); $client->setFileUpload($file->getFullPath(), 'image'); $client->setMethod('POST'); $result = $client->request()->getBody(); if (strpos($result, 'ERR') === 0) { throw new Exception("Failed uploading image: {$result}"); } if (strpos($result, 'http') === 0) { return $result; } else { return $this->config()->pixlr_temp_uri . $result; } } }
/** * @param $data * @param $url * @return mixed * @throws Zend_Http_Client_Exception */ public function krakenRequest($data, $url) { $config = array('adapter' => 'Zend_Http_Client_Adapter_Curl', 'curloptions' => array(CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36")); $client = new Zend_Http_Client($url, $config); if (isset($data['file'])) { $client->setFileUpload($data['file'], 'file'); unset($data['file']); } $client->setParameterPost($data); try { $response = $client->request('POST'); } catch (Exception $e) { Mage::log($e->getMessage(), null, 'kraken_response_error.log'); $body = array('success' => false, 'errorMessage' => $e->getMessage()); $response = new Zend_Http_Response(404, array(), json_encode($body)); } $this->_setStatusAndNotification($url, $response); $body = json_decode($response->getBody()); $body->statusCode = $response->getStatus(); return $body; }
/** * @param $data * @param $url * @return mixed * @throws Zend_Http_Client_Exception */ public function krakenRequest($data, $url) { $client = new Zend_Http_Client($url); $client->setAdapter('Zend_Http_Client_Adapter_Curl'); if (isset($data['file'])) { $client->setFileUpload($data['file'], 'file'); unset($data['file']); } $client->setParameterPost($data); try { $response = $client->request('POST'); } catch (Exception $e) { Mage::log($e->getMessage(), null, 'kraken_response_error.log'); $body = array('success' => false, 'errorMessage' => $e->getMessage()); $response = new Zend_Http_Response(404, array(), json_encode($body)); } $this->_setStatusAndNotification($url, $response); $body = json_decode($response->getBody()); $body->statusCode = $response->getStatus(); return $body; }
public function uploadPhoto($path, $name) { $session = $this->getAdapter()->getSession(); if (!($album = $this->hasAlbum($name))) { $params = array('access_token' => $session['access_token'], 'name' => $name, 'method' => 'photos.createAlbum'); $album = $this->getAdapter()->api($params); } $aid = $album['aid']; if (null === $aid) { throw new Exception('Album ID is not defined'); } $client = new Zend_Http_Client(); $client->setFileUpload($path, basename($path))->setParameterPost(array('format' => 'json', 'aid' => $aid, 'method' => 'photos.upload', 'access_token' => $session['access_token']))->setUri('https://api.facebook.com/restserver.php'); $response = $client->request(Zend_Http_Client::POST); $data = json_decode($response->getBody()); return $data->pid; }
/** * Set a file to upload (using a POST request) * * Can be used in two ways: * * 1. $data is null (default): $filename is treated as the name if a local file which * will be read and sent. Will try to guess the content type using mime_content_type(). * 2. $data is set - $filename is sent as the file name, but $data is sent as the file * contents and no file is read from the file system. In this case, you need to * manually set the Content-Type ($ctype) or it will default to * application/octet-stream. * * @param string $filename Name of file to upload, or name to save as * @param string $formname Name of form element to send as * @param string $data Data to send (if null, $filename is read and sent) * @param string $ctype Content type to use (if $data is set and $ctype is * null, will be application/octet-stream) * @return Default_Plugin_HttpBox * @throws Zend_Http_Client_Exception */ function upload($filename, $formname, $data = null, $ctype = null) { $this->client->setFileUpload($filename, $formname, $data, $ctype); return $this; }
/** * 上传指定文件名和内容的文件 * * @param string $fileName * @param bytes $fileBytes * @throws Exception * @return mixed */ public function uploadBytes($fileName, $fileBytes) { $client = new Zend_Http_Client(); $client->setUri($this->_uploadUrl); $client->setEncType(Zend_Http_Client::ENC_FORMDATA); $client->setParameterGet(array('project_id' => $this->_project_id)); $client->setFileUpload($fileName, 'file', $fileBytes); $response = $client->request('POST'); if ($response->isSuccessful()) { var_dump($response->getBody()); return json_decode(trim($response->getBody()), true); } else { throw new Exception("请求未成功"); } }
/** * Prepare the client to send the file and params in request * * @param \Zend_Http_Client $client * @param Request $request * @return void */ protected function prepareFileUpload($client, $request) { $filename = $request->getFileUpload(); $client->setFileUpload('content', 'content', file_get_contents($filename), 'application/octet-stream; charset=binary'); }
function utils_http_client($pdata = null) { //init handle $url = trim($pdata['url']); $usr = trim($pdata['usr']); $pwd = trim($pdata['pwd']); //init $client = new Zend_Http_Client(); try { //init $client->resetParameters(); $client->setUri($url); //settings $client->setConfig(array('maxredirects' => $pdata['no-redirect'] ? 0 : HTTP_CLIENT_MAX_REDIRECT, 'strictredirects' => $pdata['no-redirect'] ? true : false, 'adapter' => 'Zend_Http_Client_Adapter_Socket', 'timeout' => HTTP_CLIENT_MAX_TIMEOUT, 'keepalive' => true)); //header? if (@is_array($pdata['header'])) { $client->setHeaders($pdata['header']); } //fixed-hdrs $client->setHeaders('If-None-Match', null); $client->setHeaders('If-Modified-Since', null); //usr + pwd if (strlen($usr) and strlen($pwd)) { $client->setAuth($usr, $pwd); } //post if ($pdata['postdata']) { $client->setHeaders('Content-Type', 'application/x-www-form-urlencoded'); $client->setParameterPost($pdata['postdata']); } //upload if (@file_exists($pdata['uploadfile']) and strlen($pdata['uploadname'])) { // Uploading an existing file $client->setFileUpload($pdata['uploadfile'], $pdata['uploadname']); } //exec $response = $client->request($pdata['postdata'] ? 'POST' : 'GET'); $req_code = $response->getStatus(); $req_status = $response->isSuccessful(); $req_hdrs = $response->getHeaders(); $req_body = $response->getBody(); } catch (Zend_Http_Client_Exception $e) { $err = 'Zend_Http_Client_Exception: An error occurred (' . $e->getMessage() . ')'; debug("utils_http_client() : EXCEPTION => [ {$err} ]"); } if (HTTP_CLIENT_DEBUG) { debug("utils_http_client() : info => [ {$req_code} / {$url} / {$body} ]"); } //give it back ;-) return array('status' => (!$req_status or 200 != $req_code) ? 0 : 1, 'code' => $req_code, 'res' => $req_body, 'hdr' => $req_hdrs, 'err' => $err, 'cached' => $is_cached, 'cacheid' => $cacheid); }