Home  >  Article  >  php教程  >  PHP 实现 Ajax 无刷新图片上传

PHP 实现 Ajax 无刷新图片上传

PHP中文网
PHP中文网Original
2016-05-25 17:06:171093browse

AjaxUpload.class.php 

<?php
/*
 * Ajax 上传类库
 * @author Lee.
 * @date 2013/4/17
 */
class AjaxUpload {
    private $form_name;  //文件form名称
    private $ext_arr;    //允许上传的文件后缀
    private $upload_dir; //上传目录
    private $file_size;  //文件大小

    public function __construct($form_name, $file_size) {
        //初始化属性
        $this->form_name = $form_name;
        $this->ext_arr = array(
            &#39;.jpg&#39;,
            &#39;.png&#39;,
            &#39;.gif&#39;,
            &#39;.jpeg&#39;
        );
        $this->upload_dir = dirname(__FILE__)."/upload";
        $this->file_size = $file_size;
        $this->upload();
    }

    public function __set($key, $val) {
        $this->$key = $val;
    }

    /**
     * Ajax 无刷新上传图片(jpg|gif|png)
     * @param bool $return_arr 是否返回数组,前提是上传成功
     * @return (array)? || output
     */
    public function upload($return_arr=false) {
        if (!is_dir($this->upload_dir)) mkdir($this->upload_dir, 0777); //上传目录不存在则创建
        $file = $_FILES[$this->form_name];
        if ($file[&#39;error&#39;]==1 || $file[&#39;size&#39;]>($this->file_size*1024)) exit(&#39;1&#39;); //上传失败,图片不能大于 $this->file_size k!
        switch ($file[&#39;error&#39;]) {
            case 3:
                exit(&#39;3&#39;); //图片只有部分文件被上传,请重新上传!
                break;
            case 4:
                exit(&#39;4&#39;); //没有任何文件被上传!
                break;
        }
        $ext = $this->getExt($file[&#39;name&#39;]);
        if (!in_array($ext, $this->ext_arr)) exit(&#39;5&#39;); //非图片类型,请上传jpg|png|gif图片!
        $fname = str_replace(&#39;.&#39;, &#39;&#39;, microtime(true)) . rand(1, 9999) . $ext; //图片名称
        $filename = $this->upload_dir . &#39;/&#39; . $fname;
        if (!move_uploaded_file($file[&#39;tmp_name&#39;], $filename)) { //执行上传
            exit(&#39;upload error!&#39;); //上传失败,错误未知
        } else {
            $arr = array(&#39;ok&#39;=>1, &#39;filename&#39;=> &#39;upload/&#39; . $fname, &#39;size&#39;=>$file[&#39;size&#39;]);
            if ($return_arr) return $arr;
            else {
                echo json_encode(array(&#39;ok&#39;=>$arr[&#39;ok&#39;], &#39;filename&#39;=>$arr[&#39;filename&#39;])); exit;
            }
        }
    }

    /**
     * 获取文件后缀名
     * @param string $file_name 文件名称
     * @return string
     */
    private function getExt($file_name) {
        $ext = strtolower(strrchr($file_name, "."));
        return $ext;
    }
}
?>

2. [文件] php 实现无刷新上传.rar ~ 2MB        

PHP 实现 Ajax 无刷新图片上传php+实现无刷新上传.rar

                   

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn