ThinkPHP 6.使用上传模块(ajaxFileUpload)

下载Uploadfile类文件

http://www.thinkphp.cn/extend/224.html
放到:
ThinkPHP/Extend/Library/ORG/Net 。

修改文件头部,加上namespace:

<?php namespace Org\Net; 

官方文档位置:
http://doc.thinkphp.cn/manual/upload.html

javascript代码

 $.ajaxFileUpload({
                    url: _app_+'/Products/Items/upload',
                    secureuri: false,
                    fileElementId: 'uploadId',
                    dataType: 'json',
                    data:$("form[name=fmAdd]").serializeArray(),
                    success: function (data, status) {
                       var data_obj = JSON.parse(data);
                       console.log(data_obj);
                    },
                    error: function (data, status, e) {
                        console.log('error');
                        return;
                    }      
                });

PHP代码

  public function upload(){
    if(!isset($this->U)){
        return array('result'=>'Timeout');
    }
    // import('Org.Net.UploadFile');
    $upload = new \Org\Net\UploadFile();
    //设置上传文件大小
    //$upload->maxSize = 3292200;
    //设置上传文件类型
    $upload->allowExts = explode(',', 'txt,csv');
    //设置附件上传目录
    $upload->savePath = './Uploads/';
    if (!$upload->upload()) {
      //捕获上传异常
      //$this->error($upload->getErrorMsg());
      $this->response(array("result"=>"Fail"),'json');
    } else {
      //取得成功上传的文件信息
      $uploadList = $upload->getUploadFileInfo();
      $savename = $uploadList[0]['savename'];
      $this->response(array("result"=>"Success","url"=>$savename ),'json');
    }   
  }

html代码

 <form name="fmAdd" method="post" novalidate >
       <table class="table table-condensed">
          <tr><th>选择文件</th><td><input type="file" name="uploadId" id="uploadId" />允许文件类型:.txt .csv</td></tr>
       </table>
 </form>

你可能感兴趣的:(thinkphp)