准备事项
完成nginx相关配置,可通过url访问上传后文件
PHP FastDFS扩展安装
#进入fastdfs安装包目录下php_client文件夹
cd /fastdfs/php_client
#编译安装fastdfs_client扩展
phpize #对应要编译版本的phpize
./configure --with-php-config=/user/local/php/bin/php-config #php安装目录下的php-config
make && make install
#修改php.ini文件添加fastdfs相关配置(php_client文件夹下fastdfs_client.ini内容添加到php.ini中)
cat ./fastdfs_client.ini >> /etc/php.ini
#重启php
service php-fpm restart
#验证,查看是否有fastdfs_client扩展
php -m
#修改/etc/fdfs/client.conf
#tracker_server为保存文件的主机域名ip
PHP上传文件(YII2框架示例)
controller
public function actionFdfs()
{
$file = $_FILES ?? '';
$tmp_name = $file['file']['tmp_name'] ?? '';
$type = $file['file']['type'] ?? '';
$name = $file['file']['name'] ?? '';
$curlFile = new \CurlFile($tmp_name, $type, $name);
$fileSuffix = Common::getSuffix($curlFile->getPostFilename());
$ret['file'] = $file;
$ret['fileId'] = FastdfsUtil::uploadToFastdfs($curlFile, $fileSuffix);
return $this->asJson($ret);
}
Common相关方法
static function getSuffix($fileName)
{
preg_match('/\.(\w+)?$/', $fileName, $matchs);
return isset($matchs[1])?$matchs[1]:'';
}
FastdfsUtil
namespace app\library\common\fastdfs;
class FastdfsUtil {
//上传文件到fastdfs
static function uploadToFastdfs(\CurlFile $file, $fileSuffix)
{
$fdfs = new \FastDFS();
$tracker = $fdfs->tracker_get_connection();
$fileId = $fdfs->storage_upload_by_filebuff1(file_get_contents($file->getFilename()), $fileSuffix);
$fdfs->tracker_close_all_connections();
return $fileId;
}
}
前端页面demo(VUE上传组件)
HTML5 GetUserMedia Democlass="upload-demo"
drag
action="http://test.local/test/fdfs"
multiple>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
下载文件重命名
需调整nginx相关配置,fdfs.conf配置如下
server {
listen 8888; ## 该端口为storage.conf中的http.server_port相同
server_name localhost;
location ~/group[0-9]/ {
if ($arg_attname ~ "^(.+)") {
#设置下载
add_header Content-Type application/x-download;
#设置文件名
add_header Content-Disposition "attachment;filename=$arg_attname";
}
ngx_fastdfs_module;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}