php使用fastdfs,PHP使用FastDFS上传下载文件

准备事项

完成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 Demo

class="upload-demo"

drag

action="http://test.local/test/fdfs"

multiple>

将文件拖到此处,或 点击上传
只能上传jpg/png文件,且不超过500kb

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值