项目有一个上传APK安装包文件的需求,使用框架自带的 ‘文件’ 类型,每次都是不同路径不同文件名。希望保持固定路径和文件名所以就自己写加了一个类型,需要修改的地方如下:
1. app\common\model\Config.php 在 getTypeList 方法中添加自定义类型的英文名称
php"> 'fixedfile' => __('Fixedfile'),
2.app\admin\lang\zh-cn\general\config.php 添加对应的中文名。
php"> 'Fixedfile' => 'APK文件'
3.app\admin\view\general\config\index.html 添加类型对应的html.此处添加的是单文件上传,其中data-url="ajax/apk_upload"是自定义的上传地址。
{case value="fixedfile"}<div class="form-inline"><input id="c-{$item.name}" class="form-control" size="50" name="row[{$item.name}]" type="text" value="{$item.value|htmlentities}" data-tip="{$item.tip}"><span><button type="button" id="faupload-{$item.name}" class="btn btn-danger faupload" data-maxcount="1" data-url="ajax/apk_upload" data-input-id="c-{$item.name}" data-multiple="false" data-mimetype="apk"><i class="fa fa-upload"></i> {:__('Upload')}</button></span><span class="msg-box n-right" for="c-{$item.name}"></span></div>
{/case}
4.app\admin\controller\Ajax.php添加自定义上传方法
php"> /*** 上传文件*/public function apk_upload(){Config::set('default_return_type', 'json');//必须还原upload配置,否则分片及cdnurl函数计算错误Config::load(APP_PATH . 'extra/upload.php', 'upload');$chunkid = $this->request->post("chunkid");if ($chunkid) {if (!Config::get('upload.chunking')) {$this->error(__('Chunk file disabled'));}$action = $this->request->post("action");$chunkindex = $this->request->post("chunkindex/d");$chunkcount = $this->request->post("chunkcount/d");$filename = $this->request->post("filename");$method = $this->request->method(true);if ($action == 'merge') {$attachment = null;//合并分片文件try {$upload = new Upload();$attachment = $upload->merge($chunkid, $chunkcount, $filename);} catch (UploadException $e) {$this->error($e->getMessage());}$this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);} elseif ($method == 'clean') {//删除冗余的分片文件try {$upload = new Upload();$upload->clean($chunkid);} catch (UploadException $e) {$this->error($e->getMessage());}$this->success();} else {//上传分片文件//默认普通上传文件$file = $this->request->file('file');try {$upload = new Upload($file);$upload->chunk($chunkid, $chunkindex, $chunkcount);} catch (UploadException $e) {$this->error($e->getMessage());}$this->success();}} else {$attachment = null;//默认普通上传文件$file = $this->request->file('file');try {$upload = new Upload($file);$attachment = $upload->upload('/upload/apk/app_down.apk');} catch (UploadException $e) {$this->error($e->getMessage());}$this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);}}
代码中的/upload/apk/app_down.apk是文件路径,也可以在data-url中添加路径,但有弊端所以放弃,可以参考:上传图片自定义文件夹方法
以上就通过自定义配置实现了上传文件保持固定路径和名称的功能。