PHP使用原生函數(shù)實(shí)現(xiàn)文件上傳及下載
文件上傳:
if ( $_FILES && $_FILES[’attachment’] && $_FILES[’attachment’][’tmp_name’]){ $filesize = $_FILES[’attachment’][’size’]; //文件上傳大小限制:5M if($filesize > 5*1024*1024){exit(’上傳文件大小超出限制!’); } //文件保存目錄,如果不存在則創(chuàng)建之 $uploaddir = ROOT_DIR.’/public/attachment/notice/’; if(!file_exists($uploaddir))mkdir($uploaddir,0755,true); //獲取上傳文件擴(kuò)展名 $arr_file = explode(’.’, basename($_FILES[’attachment’][’name’])); $filetype = $arr_file[count($arr_file)-1]; //獲取源文件名 $attachment_name = basename($_FILES[’attachment’][’name’]); //對(duì)文件進(jìn)行重命名以避免中文字符的影響 $fname = md5(basename($_FILES[’attachment’][’name’]).microtime()).’.’.$filetype; $uploadfile = $uploaddir . $fname; if (move_uploaded_file($_FILES[’attachment’][’tmp_name’], $uploadfile)) {//獲取文件相對(duì)路徑$attachment = ’/public/attachment/notice/’. $fname; } else {exit(’文件上傳失敗!’); }}
注:'attachment'是上傳文件name,根據(jù)項(xiàng)目中的具體屬性值修改之。本上傳處理未對(duì)文件類型做限制處理,可根據(jù)具體需求自己處理之。
文件下載:
//輸入文件標(biāo)簽 Header ( 'Content-type: application/octet-stream' ); Header ( 'Accept-Ranges: bytes' ); Header ( 'Accept-Length: ' . filesize ( $attachment_filepath ) ); Header ( 'Content-Disposition: attachment; filename=' . $attachment_filename ); //輸出文件內(nèi)容 //讀取文件內(nèi)容并直接輸出到瀏覽器 echo file_get_contents($attachment_filepath); exit ();
相關(guān)文章:
1. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問(wèn)題2. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)3. Springboot 全局日期格式化處理的實(shí)現(xiàn)4. idea配置jdk的操作方法5. Docker容器如何更新打包并上傳到阿里云6. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法7. VMware中如何安裝Ubuntu8. python 浮點(diǎn)數(shù)四舍五入需要注意的地方9. JAMon(Java Application Monitor)備忘記10. vue實(shí)現(xiàn)web在線聊天功能
