upload_file_by_content() публичный Метод

通过在http body中添加内容来上传文件,适合比较小的文件 根据api约定,需要在http header中增加content-length字段
С версии: 2011-11-14
Автор: xiaobing.meng@alibaba-inc.com
public upload_file_by_content ( string $bucket, string $object, array $options = null ) : ResponseCore
$bucket string (Required)
$object string (Required)
$options array (Optional)
Результат ResponseCore
Пример #1
0
 private function upload($data)
 {
     $data = explode('|', $data);
     $ch = curl_init($data[1]);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     $img = curl_exec($ch);
     $info = curl_getinfo($ch);
     if (curl_errno($ch) > 0) {
         curl_close($ch);
         echo "{$data[1]} | {$data[0]} Failed \n";
         return;
     }
     curl_close($ch);
     require_once APP_DIR . 'vendors/objectstorage/sdk.class.php';
     require_once APP_DIR . 'vendors/objectstorage/util/oss_util.class.php';
     $oss = new \ALIOSS(OSS_ACCESS_ID, OSS_ACCESS_KEY, OSS_ENDPOINT);
     $object = "avatar/{$data[0]}";
     $content = $img;
     $options = array('Content-Type' => $info['content_type'], 'content' => $content, 'length' => strlen($content));
     $res = $oss->upload_file_by_content(OSS_TEST_BUCKET, $object, $options);
     \OSSUtil::print_res($res, "{$data[1]} | {$data[0]}");
     if (!$this->user->update(['avatar' => time()], ['uid' => $data[0]])) {
         echo " database updated failed. \n";
     }
 }
Пример #2
0
 /**
  * @param  上传图片到aliyun oss
  * @param  [obj] 阿里云sdk  可不填
  * @param  [imgName] 图片名称
  * @param  [content] 图片地址
  * @param  [save_type] 保存图片时的模式  url=>表示传入url 上传 否则为图片的源数据
  * @return [ossImgUrl]
  */
 public function upload_by_content($obj = "", $imgName, $content, $save_type = 'url')
 {
     if (empty($obj)) {
         /**
          * 加载sdk包以及错误代码包
          */
         $sdkPath = dirname(__FILE__);
         require_once $sdkPath . '/sdk.class.php';
         $obj = new ALIOSS();
         //设置是否打开curl调试模式
         //$obj->set_debug_mode(FALSE);
         //设置开启三级域名,三级域名需要注意,域名不支持一些特殊符号,所以在创建bucket的时候若想使用三级域名,最好不要使用特殊字符
         $obj->set_enable_domain_style(TRUE);
     }
     $bucket = QRIMG_B;
     $folder = 'headimg/';
     $object = $folder . $imgName;
     if ($save_type == 'url') {
         $content = file_get_contents($content);
     } else {
         $content = $content;
     }
     $upload_file_options = array('content' => $content, 'length' => strlen($content), ALIOSS::OSS_HEADERS => array('Expires' => date('Y-m-d H:i:s', time() + 3600 * 24 * 10)));
     $response = $obj->upload_file_by_content($bucket, $object, $upload_file_options);
     //echo 'upload file {'.$object.'}'.($response->isOk()?'ok':'fail')."\n";
     //_format($response);
     return HTTP_IMG_HOST . $object;
 }
Пример #3
0
 protected function publish($dat = [])
 {
     $id = (int) $dat['id'];
     $htm = '';
     if ($id) {
         $dat = D(CONTROLLER_NAME)->complete_fields($dat);
         $this->data = ['item' => $dat];
         layout(false);
         $htm = $this->fetch('view');
         $fnm = 'article/content/' . $id . '.html';
         import('Org.AliyunOss.sdk');
         $oss = new \ALIOSS();
         $oss->delete_object('cjstatic', $fnm);
         $ret = $oss->upload_file_by_content('cjstatic', $fnm, ['content' => $dat['content'], 'Content-Encoding' => 'UTF-8', 'Expires' => date('Y-m-d H:i:s', strtotime('1 days'))]);
     }
     return $dat;
 }
Пример #4
0
/**
 * 在OSS中记录日志信息
 * @param $logpath 日志存放路径
 * @param $content 写入的内容
 * @return bool
 */
function _logged($logpath, $content)
{
    //获取WP配置信息
    $oss_options = get_option('oss_options', TRUE);
    $oss_bucket = attribute_escape($oss_options['bucket']);
    $oss_ak = attribute_escape($oss_options['ak']);
    $oss_sk = attribute_escape($oss_options['sk']);
    $oss_host = attribute_escape($oss_options['host']);
    if ($oss_host == null || $oss_host == '') {
        $oss_host = 'oss.aliyuncs.com';
    }
    try {
        //实例化存储对象
        if (!is_object($aliyun_oss)) {
            $aliyun_oss = new ALIOSS($oss_ak, $oss_sk, $oss_host);
        }
        //上传原始文件,$opt暂时没有使用
        $upload_file_options = array('content' => $content, 'length' => strlen($content), ALIOSS::OSS_HEADERS => array('Expires' => '2012-10-01 08:00:00'));
        $aliyun_oss->upload_file_by_content($oss_bucket, $logpath, $upload_file_options);
        return TRUE;
    } catch (Exception $ex) {
        return FALSE;
    }
}
Пример #5
0
    public function createChromeBak($service)
    {
        $server = $this->getServerByIp($service->server);
        $chrome = <<<STR
{"-confirmDeletion":true,"-downloadInterval":720,"-enableQuickSwitch":false,"-exportLegacyRuleList":true,"-monitorWebRequests":true,"-quickSwitchProfiles":[],"-refreshOnProfileChange":false,"-revertProxyChanges":false,"-showInspectMenu":true,"-startupProfileName":"","schemaVersion":2,"+全局代理":{"bypassList":[{"conditionType":"BypassCondition","pattern":"<local>"}],"color":"#9d9","fallbackProxy":{"host":"{[:server]}","port":{[:port]},"scheme":"socks5"},"name":"全局代理","profileType":"FixedProfile","revision":"14f69ea40f6"},"+智能分流":{"color":"#d497ee","lastUpdate":"","name":"智能分流","pacScript":"","pacUrl":"{[:pacUrl]}","profileType":"PacProfile","revision":"14f6a201b1f"},"+自动切换":{"profileType":"SwitchProfile","name":"自动切换","defaultProfileName":"智能分流","rules":[],"color":"#9ce","revision":"14f6a1fbe64"}}
STR;
        $chrome = str_replace(['{[:server]}', '{[:port]}', '{[:pacUrl]}'], [$server, $service->port, $service->pac], $chrome);
        $filename = substr(md5($server . ":" . $service->port), 8, 16) . '.bak';
        $options = ['content' => $chrome];
        Yii::import('ext.oss_php_sdk_20150819.alioss', true);
        $alioss = new ALIOSS(OSS_ACCESS_ID, OSS_ACCESS_KEY, OSS_ENDPOINT);
        $response = $alioss->upload_file_by_content(OSS_BUCKET, "chrome/" . $filename, $options);
        if ($response->status == 200) {
            return true;
        } else {
            return false;
        }
    }
Пример #6
0
 /**
  * 上传文件的主处理方法
  * @return mixed
  */
 private function upFile()
 {
     $file = $this->file = $_FILES[$this->fileField];
     if (!$file) {
         $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
         return;
     }
     if ($this->file['error']) {
         $this->stateInfo = $this->getStateInfo($file['error']);
         return;
     } else {
         if (!file_exists($file['tmp_name'])) {
             $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
             return;
         } else {
             if (!is_uploaded_file($file['tmp_name'])) {
                 $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
                 return;
             }
         }
     }
     $this->oriName = $file['name'];
     $this->fileSize = $file['size'];
     $this->fileType = $this->getFileExt();
     $this->fullName = $this->getFullName();
     $this->filePath = $this->getFilePath();
     $this->fileName = $this->getFileName();
     $dirname = dirname($this->filePath);
     //检查文件大小是否超出限制
     if (!$this->checkSize()) {
         $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
         return;
     }
     //检查是否不允许的文件格式
     if (!$this->checkType()) {
         $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
         return;
     }
     //移动文件
     $SCRIPT_FILENAME = $_SERVER["SCRIPT_FILENAME"];
     $SCRIPT_FILENAME = explode('webroot', $SCRIPT_FILENAME);
     $this->filePath = 'activitys/' . $_REQUEST['activityId'] . '/' . $this->fileName;
     include $SCRIPT_FILENAME[0] . 'webroot/aliyun2/sdk.class.php';
     $file = file_get_contents($file['tmp_name']);
     $uploadFileoptions = array('content' => $file, 'length' => $this->fileSize);
     $oss_sdk_service = new ALIOSS();
     $rest = $oss_sdk_service->upload_file_by_content("open-edit", $this->filePath, $uploadFileoptions);
     $thumbpath = $rest->header['x-oss-request-url'];
     $this->fullName = str_replace('oss-cn-hangzhou.aliyuncs.com/open-edit', 'cdn.open.easytee.me', $thumbpath);
     $this->stateInfo = 'SUCCESS';
 }
Пример #7
0
 /**
  * 修改文件处理函数
  *
  * @access public
  * @param array $content 老文件
  * @param array $file 新上传的文件
  * @return mixed
  */
 public static function modifyHandle($content, $file)
 {
     if (empty($file['name'])) {
         return false;
     }
     $fileName = preg_split("(\\/|\\|:)", $file['name']);
     $file['name'] = array_pop($fileName);
     //获取扩展名
     $ext = '';
     $part = explode('.', $file['name']);
     if (($length = count($part)) > 1) {
         $ext = strtolower($part[$length - 1]);
     }
     if ($content['attachment']->type != $ext) {
         return false;
     }
     //获取文件名
     $fileName = $content['attachment']->path;
     $path = $path . '/' . $fileName;
     //add for mkdir
     $path = substr($path, 1);
     $options = Typecho_Widget::widget('Widget_Options');
     $access_id = $options->plugin('AliUpload')->access_id;
     $access_key = $options->plugin('AliUpload')->access_key;
     $bucket = $options->plugin('AliUpload')->bucket;
     $oss_service = new ALIOSS($access_id, $access_key);
     if (isset($file['tmp_name'])) {
         //移动上传文件
         $response = $oss_service->upload_file_by_file($bucket, $path, $file['tmp_name']);
         if (!$response->isOk()) {
             return false;
         }
     } else {
         if (isset($file['bits'])) {
             //直接写入文件
             $upload_file_options = array('content' => $file['bits'], 'length' => strlen($file['bits']));
             $response = $oss_service->upload_file_by_content($bucket, $path, $upload_file_options);
             if (!$response->isOk()) {
                 return false;
             }
         } else {
             return false;
         }
     }
     if (!isset($file['size'])) {
         $file['size'] = $response->header['_info']['size_upload'];
     }
     //返回相对存储路径
     return array('name' => $content['attachment']->name, 'path' => $content['attachment']->path, 'size' => $file['size'], 'type' => $content['attachment']->type, 'mime' => $content['attachment']->mime);
 }