准备事项
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框架示例)
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);
}
static function getSuffix($fileName)
{
preg_match('/\.(\w+)?$/', $fileName, $matchs);
return isset($matchs[1])?$matchs[1]:'';
}
<?php
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上传组件)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML5 GetUserMedia Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
</head>
<body>
<div id="app">
<el-upload
class="upload-demo"
drag
action="http://test.local/test/fdfs"
multiple>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
</script>
</body>
</html>
下载文件重命名
- 需调整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;
}
}
网友评论