Upload an image to Imageshack

@param string File you will be uploading (URL, Base64)
@param string Description of image
@return mixed Response
438412
public function upload($file, $format = 'json')
	{
		// Is this "file" a URL?
		$url = filter_var($file, FILTER_VALIDATE_URL) !== false;

		$data = array(
			'key' => $this->key,
			'format' => $format
		);

		if ($url) {
			$data['url'] = $file;
		} else {
			$data['fileupload'] = $file;
		}

		if ($this->credentials) {
			$data['a_username'] = $this->credentials['username'];
			$data['a_password'] = $this->credentials['password'];
		} else if($this->cookie) {
			$data['cookie'] = $this->cookie;
		}

		return $this->post('https://post.imageshack.us/upload_api.php', $data);
	}
672435
function addFile(file) {
                var $li = $('<li id="' + file.id + '">' +
                        '<p class="title">' + file.name + '</p>' +
                        '<p class="imgWrap"></p>' +
                        '<p class="progress"><span></span></p>' +
                        '</li>'),

                    $btns = $('<div class="file-panel">' +
                        '<span class="cancel">' + lang.uploadDelete + '</span>' +
                        '<span class="rotateRight">' + lang.uploadTurnRight + '</span>' +
                        '<span class="rotateLeft">' + lang.uploadTurnLeft + '</span></div>').appendTo($li),
                    $prgress = $li.find('p.progress span'),
                    $wrap = $li.find('p.imgWrap'),
                    $info = $('<p class="error"></p>').hide().appendTo($li),

                    showError = function (code) {
                        switch (code) {
                            case 'exceed_size':
                                text = lang.errorExceedSize;
                                break;
                            case 'interrupt':
                                text = lang.errorInterrupt;
                                break;
                            case 'http':
                                text = lang.errorHttp;
                                break;
                            case 'not_allow_type':
                                text = lang.errorFileType;
                                break;
                            default:
                                text = lang.errorUploadRetry;
                                break;
                        }
                        $info.text(text).show();
                    };

                if (file.getStatus() === 'invalid') {
                    showError(file.statusText);
                } else {
                    $wrap.text(lang.uploadPreview);
                    if ('|png|jpg|jpeg|bmp|gif|'.indexOf('|'+file.ext.toLowerCase()+'|') == -1) {
                        $wrap.empty().addClass('notimage').append('<i class="file-preview file-type-' + file.ext.toLowerCase() + '"></i>' +
                            '<span class="file-title">' + file.name + '</span>');
                    } else {
                        if (browser.ie && browser.version <= 7) {
                            $wrap.text(lang.uploadNoPreview);
                        } else {
                            uploader.makeThumb(file, function (error, src) {
                                if (error || !src || (/^data:/.test(src) && browser.ie && browser.version <= 7)) {
                                    $wrap.text(lang.uploadNoPreview);
                                } else {
                                    var $img = $('<img src="' + src + '">');
                                    $wrap.empty().append($img);
                                    $img.on('error', function () {
                                        $wrap.text(lang.uploadNoPreview);
                                    });
                                }
                            }, thumbnailWidth, thumbnailHeight);
                        }
                    }
                    percentages[ file.id ] = [ file.size, 0 ];
                    file.rotation = 0;

                    /* 检查文件格式 */
                    if (!file.ext || acceptExtensions.indexOf(file.ext.toLowerCase()) == -1) {
                        showError('not_allow_type');
                        uploader.removeFile(file);
                    }
                }

                file.on('statuschange', function (cur, prev) {
                    if (prev === 'progress') {
                        $prgress.hide().width(0);
                    } else if (prev === 'queued') {
                        $li.off('mouseenter mouseleave');
                        $btns.remove();
                    }
                    // 成功
                    if (cur === 'error' || cur === 'invalid') {
                        showError(file.statusText);
                        percentages[ file.id ][ 1 ] = 1;
                    } else if (cur === 'interrupt') {
                        showError('interrupt');
                    } else if (cur === 'queued') {
                        percentages[ file.id ][ 1 ] = 0;
                    } else if (cur === 'progress') {
                        $info.hide();
                        $prgress.css('display', 'block');
                    } else if (cur === 'complete') {
                    }

                    $li.removeClass('state-' + prev).addClass('state-' + cur);
                });

                $li.on('mouseenter', function () {
                    $btns.stop().animate({height: 30});
                });
                $li.on('mouseleave', function () {
                    $btns.stop().animate({height: 0});
                });

                $btns.on('click', 'span', function () {
                    var index = $(this).index(),
                        deg;

                    switch (index) {
                        case 0:
                            uploader.removeFile(file);
                            return;
                        case 1:
                            file.rotation += 90;
                            break;
                        case 2:
                            file.rotation -= 90;
                            break;
                    }

                    if (supportTransition) {
                        deg = 'rotate(' + file.rotation + 'deg)';
                        $wrap.css({
                            '-webkit-transform': deg,
                            '-mos-transform': deg,
                            '-o-transform': deg,
                            'transform': deg
                        });
                    } else {
                        $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
                    }

                });

                $li.insertBefore($filePickerBlock);
            }
738235
public function upload($file, $path='')
	{
		$path = ltrim($path, '/');
		$path = rtrim($path, '/');
		$basePath = $this->getImageBasePath();
		$imagePath = $basePath.'/'.$path;

		if (!File::exists($imagePath)) {
			throw new ImageUploaderException("Directory {$path} doesn't exists");
		}

		$uploadedFile = $this->getUploadedFile($file);
		$fileName = $this->generateFileName($uploadedFile->getClientOriginalExtension());
		$uploadedFile->move($imagePath, $fileName);

		if (!is_null($this->temporaryImage)) {
			File::delete($this->temporaryImage);
		}

		return $path.'/'.$fileName;
	}
480157
public function update($file = null)
	{
		$file = ($file ?: $this->file);

		$contents = $this->toString('PHP', array('class' => 'JConfig', 'closingtag' => false));
		$original = '0640';

		if (is_file($file))
		{
			// Track original permissions
			$original = '0' . decoct(fileperms($file) & 0777);

			// First try and make sure the file is writable
			@chmod($file, octdec('0640'));
		}

		$result = file_put_contents($file, $contents);

		if (is_file($file))
		{
			@chmod($file, octdec($original));
		}

		return $result;
	}
889885
public function upload($name = null, $file = null, $params = ['path' => '','afterUpload' => null, 'beforeUpload' => null, 'coords' => null, 'width' => null, 'height' => null, 'beforeUploadImage' => null, 'preserveIfGif' => false]){

        Arr::mergeWithDefaultParams($params);

        $data = [];

        if($file){
            $data['file'] = $file;
        } elseif(Input::hasFile('file')){
            $data['file'] = Input::file('file');
        }   else {
            trigger_error("File doesn't exist.");
        }

        $data['name'] = $name;

        $data['params'] = $params;

        $data['response'] = false;

        $data['path'] = $this->relPath();

        $data['fullname'] = $data['file']->getClientOriginalName();

        $data['extension'] = $data['file']->getExtension() ?: $data['file']->getClientOriginalExtension();
        $data['mimeType'] = $data['file']->getMimeType();

        if(in_array($data['mimeType'], ['image/gif', 'image/jpeg', 'image/png'])){
            $data['type'] = "image";
        } else {
            $data['type'] = "file";
        }

        if(!$data['name']){
            $data['name'] = $data['file']->getClientOriginalName();
        } elseif(strpos($data['name'], '.') && !preg_match('/\.'.$data['extension'].'$/i', $data['name'])){
            $data['convert'] = true;
        } elseif(!strpos($data['name'], '.')){
            $data['name'] = $data['name'] . '.' . $data['extension'];
        }

        if($params['beforeUpload']){
            $data = $params['beforeUpload']($data);
        }

        if ($params['path']) {
            try {
                if(!is_dir(public_path($data['path'].$params['path'])))
                    mkdir(public_path($data['path'].$params['path']), 0777, true);
            } catch (Exception $e) {
                Api::handleError($e);
                return Api::responseJsonError($e);
            }
        }

        if($data['extension'] == "gif" && $params['preserveIfGif']){
            $data['response'] = $data['file']->move(public_path($data['path'] .$params['path']), $data['name']);
        } elseif($data['type'] == 'image'){

            $img = Image::load($data['file']->getRealPath());

            if($data['params']['coords']){
                $coords = $data['params']['coords'];
                if (!is_array($coords)) {
                    $coords = json_decode(stripslashes($coords), true);
                }
                $img->crop($coords['x'], $coords['y'], $coords['x'] + $coords['w'], $coords['y'] + $coords['h']);
            } elseif($data['params']['width'] && $data['params']['height']) {
                $img->resize($data['params']['width'], $data['params']['height']);
            } elseif($data['params']['width']){
                $img->fit_to_width($data['params']['width']);
            } elseif($data['params']['height']) {
                $img->fit_to_width($data['params']['height']);
            }

            if($params['beforeUploadImage']){
                $img = $params['beforeUploadImage']($img);
            }

            $data['response'] = $img->save(public_path($data['path'] .$params['path']. $data['name']));

        } else {
            $data['response'] = $data['file']->move(public_path($data['path'] .$params['path']), $data['name']);
        }

        if($params['afterUpload']){
            $data = $params['afterUpload']($data);
        }

        if (isset($data['path'], $data['name'])) {
            $data['relpath'] = self::cleanPath($data['path'] . $data['name']);
        }

        return $data;
    }
1289124
def upload(status, file, query={})
      PostBodyHack.apply_hack({:status => status}.merge(query)) do
        perform_post("/statuses/upload.json", build_multipart_bodies({:pic => file, :status => status}.merge(query)))
      end
    end
1291223
public function save($file = NULL)
    {
        if(is_null($file) && $this->storage)
        {
            $this->storage->save($this);
        }
        elseif(!is_null($file))
        {
            $this->savePicture($file);
        }
        else
        {
            trigger_error('Image file to save is not defined', E_USER_WARNING);
        }
    }
490473
public function upload($file, $to = null)
    {
        if ($this->test($file)) {
            if (null === $to) {
                $to = $file['name'];
            }
            if (!$this->overwrite) {
                $to = $this->checkFilename($to);
            }

            $this->uploadedFile = $to;
            $to = $this->uploadDir . DIRECTORY_SEPARATOR . $to;

            // Move the uploaded file, creating a file object with it.
            if (move_uploaded_file($file['tmp_name'], $to)) {
                return $this->uploadedFile;
            } else {
                $this->error = self::UPLOAD_ERR_UNEXPECTED;
                return false;
            }
        } else {
            return false;
        }

    }
72351
public function upload($file)
    {
        if ($this->isSubmodule) {
            $file = $this->isSubmodule.'/'.$file;
        }

        $dir = explode('/', dirname($file));
        $path = '';
        $pathThatExists = null;
        $output = array();

        // Skip basedir or parent.
        if ($dir[0] != '.' and $dir[0] != '..') {
            // Iterate through directory pieces.
            for ($i = 0, $count = count($dir); $i < $count; $i++) {
                $path .= $dir[$i].'/';

                if (!isset($pathThatExists[$path])) {
                    $origin = $this->bridge->pwd();

                    // The directory doesn't exist.
                    if (! $this->bridge->exists($path)) {
                        // Attempt to create the directory.
                        $this->bridge->mkdir($path);
                        $output[] = "Created directoy '$path'.'";
                    }
                    // The directory exists.
                    else {
                        $this->bridge->cd($path);
                    }

                    $pathThatExists[$path] = true;
                    $this->bridge->cd($origin);
                }
            }
        }

        $uploaded = false;
        $attempts = 1;

        // Loop until $uploaded becomes a valid
        // resource.
        while (!$uploaded) {
            // Attempt to upload the file 10 times
            // and exit if it fails.
            if ($attempts == 10) {
                $output[] = "Tried to upload $file 10 times, and failed 10 times. Something is wrong, so I'm going to stop executing now.";
                return $output;
            }

            $data = file_get_contents($file);
            $uploaded = $this->bridge->put($data, $file);

            if (!$uploaded) {
                $attempts++;
            }
        }

        $output[] = "√ \033[0;37m{$file}\033[0m \033[0;32muploaded\033[0m";

        return $output;
    }
706170
protected function createUploadedFile($file)
	{
		try {
			$imageManager = new ImageManager;
			$image = $imageManager->make($file);
			$extension = $this->getExtensionFromMime($image->mime());
			$fileName = $this->generateFileName($extension);
			$temporaryPath = $this->getTemporaryImageBasePath();
			$this->temporaryImage = $temporaryPath.'/'.$fileName;
			$image->save($this->temporaryImage);

			return new UploadedFile(
				$this->temporaryImage,
				$fileName, 
				$image->mime(),
				$image->filesize(),
				null,
				TRUE
			);
		} catch (Exception $e) {
			throw new ImageUploaderException("Error create uploaded file");
		}
	}
290746
public function send_file($file) {
        // First we create the 'resumable upload request'.
        $this->googleoauth->setHeader("Content-Length: 0");
        $this->googleoauth->setHeader("X-Upload-Content-Length: ". $file->get_filesize());
        $this->googleoauth->setHeader("X-Upload-Content-Type: ". $file->get_mimetype());
        $this->googleoauth->setHeader("Slug: ". $file->get_filename());
        $this->googleoauth->post(self::UPLOAD_URL);

        if ($this->googleoauth->info['http_code'] !== 200) {
            throw new moodle_exception('Cantpostupload');
        }

        // Now we http PUT the file in the location returned.
        $location = $this->googleoauth->response['Location'];
        if (empty($location)) {
            throw new moodle_exception('Nouploadlocation');
        }

        // Reset the curl object for actually sending the file.
        $this->reset_curl_state();
        $this->googleoauth->setHeader("Content-Length: ". $file->get_filesize());
        $this->googleoauth->setHeader("Content-Type: ". $file->get_mimetype());

        // We can't get a filepointer, so have to copy the file..
        $tmproot = make_temp_directory('googledocsuploads');
        $tmpfilepath = $tmproot.'/'.$file->get_contenthash();
        $file->copy_content_to($tmpfilepath);

        // HTTP PUT the file.
        $this->googleoauth->put($location, array('file'=>$tmpfilepath));

        // Remove the temporary file we created..
        unlink($tmpfilepath);

        if ($this->googleoauth->info['http_code'] === 201) {
            // Clear headers for further requests.
            $this->reset_curl_state();
            return true;
        } else {
            return false;
        }
    }
947903
private function upload($file)
    {
        $file = $this->model->createFile($this->attribute, $file->tempName, $file->name);
        if ($file) {
            if ($this->saveAfterUpload) {
                $this->model->save(false);
            }
            $presetAfterUpload = $this->model->filePresetAfterUpload($this->attribute);
            if (count($presetAfterUpload)) {
                $this->applyPreset($presetAfterUpload, $file);
            }
            $template = $this->model->fileOption($this->attribute, 'template');
            if ($template) {
                return $this->response(
                    $this->controller->renderFile(Yii::getAlias($template), [
                        'file' => $file,
                        'model' => $this->model,
                        'attribute' => $this->attribute
                    ])
                );
            }
            return $this->response([
                $this->resultFieldId => $file->getPrimaryKey(),
                $this->resultFieldPath => $this->model->fileUrl($this->attribute, $file),
            ]);
        }
        return $this->response(['error' => Yii::t('filemanager-yii2', 'Error saving file')]); // @codeCoverageIgnore
    }
1038911
public String uploadFile(File file) throws IOException {
        HttpPost post = null;
        try {
            // prepare the post method
            post = new HttpPost(getUploadURL());
            post.getParams().setParameter("Connection", "Keep-Alive");

            // add the file part
            MultipartEntity entity = new MultipartEntity();
            entity.addPart("file", new FileBody(file));
            post.setEntity(entity);

            // execute and get the response
            HttpResponse response = getHttpClient().execute(post);
            int responseCode = response.getStatusLine().getStatusCode();
            String body = null;
            try {
                if (response.getEntity() != null) {
                    body = EntityUtils.toString(response.getEntity());
                }
            } catch (Exception e) {
                logger.warn("Error reading response body", e);
            }
            if (body == null) {
                body = "[empty response body]";
            }
            body = body.trim();
            if (responseCode != HttpStatus.SC_CREATED) {
                throw new IOException("Upload failed: "
                        + response.getStatusLine().getReasonPhrase()
                        + ": " + replaceNewlines(body, " "));
            } else {
                return replaceNewlines(body, "");
            }
        } finally {
            if (post != null) {
                post.releaseConnection();
            }
        }
    }
1095866
public function setImage($file) {

		if(false === is_string($file)) {
			return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($file)), E_USER_ERROR);
		}

		if(false === is_file($file)) {
			return trigger_error(sprintf('File "%s" passed to %s() does not exists', $file, __METHOD__), E_USER_ERROR);
		}

		if(false === is_readable($file)) {
			return trigger_error(sprintf('File "%s" passed to %s() is not readable', $file, __METHOD__), E_USER_ERROR);
		}

		$info = @getimagesize($file);

		if(false === is_array($info) || count($info) < 3) {
			return trigger_error(sprintf('File "%s" passed to %s() is not an image', $file, __METHOD__), E_USER_ERROR);
		}

		$this -> image 	 	= @imagecreatefromstring(file_get_contents($file));
		$this -> extension 	= pathinfo($file, PATHINFO_EXTENSION);

		return $this;
	}
1336320
public function processImage( $file, $width = null, $height = null, $mwidth = null, $mheight = null, $twidth = null, $theight = null ) {

		$dateDir	= date( 'Y-m-d' );
		$imageName	= $file->name;
		$imageExt	= $file->extension;
		$imageDir	= $file->directory;

		$uploadDir	= $this->uploadDir;

		$sourceFile	= "$imageDir/$imageName.$imageExt";
		$targetDir	= "$dateDir/$imageDir/";

		$imageUrl		= $targetDir . "$imageName.$imageExt";
		$imageMediumUrl	= $targetDir . "$imageName-medium.$imageExt";
		$imageThumbUrl	= $targetDir . "$imageName-thumb.$imageExt";

		// Update File Size in MB
		$fileContent	= file_get_contents( "$uploadDir/temp/$sourceFile" );
		$file->size		= number_format( strlen( $fileContent ) / 1048576, 8 );

		// Save Image
		$this->saveImage( $sourceFile, $targetDir, $imageUrl, $imageMediumUrl, $imageThumbUrl, $width, $height, $mwidth	 = null, $mheight = null, $twidth	 = null, $theight = null );

		// Update URL and Thumb
		$file->url = $imageUrl;

		if( $this->generateImageMedium ) {

			$file->medium = $imageMediumUrl;
		}

		if( $this->generateImageThumb ) {

			$file->thumb = $imageThumbUrl;
		}
	}
318651
public function upload($imageFile)
    {
        if ($imageFile instanceof UploadedFile) {
            if ($imageFile->isValid()) {
                $pictureId = $this->pictureIdGenerator->generate($imageFile);
                if(false === $this->disk->putFileAs('', $imageFile, $this->pictureUrlManager->getOriginalPath($pictureId))){
                    throw new UploadException();
                }
                return $pictureId;
            } else {
                throw new UploadException($imageFile->getErrorMessage());
            }
        } else {
            throw new UploadException();
        }
    }
1362478
public function upload()
    {
        //as upload may be called multiple times, we remove the session lock as soon as possible
        try{
            session_write_close();
            if ($this->hasRequestParameter('uri')) {
                $itemUri = $this->getRequestParameter('uri');
                $item = $this->getResource($itemUri);
            }

            if ($this->hasRequestParameter('lang')) {
                $itemLang = $this->getRequestParameter('lang');
            }

            if (!$this->hasRequestParameter('path')) {
                throw new common_exception_MissingParameter('path', __METHOD__);
            }

            if (!$this->hasRequestParameter('filters')) {
                throw new common_exception_MissingParameter('filters', __METHOD__);
            }
            $filters = $this->getRequestParameter('filters');

            $resolver = new ItemMediaResolver($item, $itemLang);
            $asset = $resolver->resolve($this->getRequestParameter('relPath'));

            $file = tao_helpers_Http::getUploadedFile('content');
            $fileTmpName = $file['tmp_name'].'_'.$file['name'];

            if (!tao_helpers_File::copy($file['tmp_name'], $fileTmpName)) {
                throw new common_exception_Error('impossible to copy '.$file['tmp_name'].' to '.$fileTmpName);
            }

            $mime = \tao_helpers_File::getMimeType($fileTmpName);
            if (is_string($filters)) {
                // the mime type is part of the $filters
                $filters = explode(',', $filters);
                if ((in_array($mime, $filters))) {
                    $filedata = $asset->getMediaSource()->add($fileTmpName, $file['name'],
                        $asset->getMediaIdentifier());
                } else {
                    throw new FileUploadException(__('The file you tried to upload is not valid'));
                }
            } else {
                $valid = false;
                // OR the extension is part of the filter and it correspond to the mime type
                foreach ($filters as $filter) {
                    if ($filter['mime'] === $mime &&
                        (!isset($filter['extension']) || $filter['extension'] === \tao_helpers_File::getFileExtention($fileTmpName))
                    ) {
                        $valid = true;
                    }
                }
                if ($valid) {
                    $filedata = $asset->getMediaSource()->add($fileTmpName, $file['name'],
                        $asset->getMediaIdentifier());
                } else {
                    throw new FileUploadException(__('The file you tried to upload is not valid'));
                }
            }

            $this->returnJson($filedata);
            return;
        }
        catch(PermissionException $e){
            $message = $e->getMessage();
        }
        catch(FileUploadException $e){
            $message = $e->getMessage();
        }
        catch(common_Exception $e){
            $this->logWarning($e->getMessage());
            $message = _('Unable to upload file');
        }
        $this->returnJson(array('error' => $message));

    }