一、大文件上传:
- 将php.ini上传文件限制参数放大,最好php7版本,不然大于2G会有问题
file_uploads = On #文件上传需要开启
max_execution_time = 600 # 每个php脚本执行最大时间秒
max_input_time = 600 # 每个php接受数据执行最大时间秒
memory_limit = 300m #每个PHP页面所吃掉的最大内存
post_max_size = 250m #接受post数据最大限制
upload_max_filesize =200m #接受上传文件的最大限制
#要保证这样
memory_limit > post_max_size > upload_max_filesize
- 分片上传,使用plupload等组件来实,需要html5浏览器支持,但是合并的时候注意标识按顺序合并
- 请求接口,服务端创建一个分片上传的“队列”
- 请求接口,上传文件,指定分片索引 index
- 所有分片上传完成,请求服务端接口合并文件,依据index顺序。
send_timeout 60;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
client_max_body_size 30m; #这个是关键参数,默认是2m可以全局设置也可以每个网站单独设置
php.ini修改就是上面的地方
php-fpm
request_terminate_timeout 300
request_slowlog_timeout 如果多数为上传大文件则设置较大值,这个根据自身情况设置
- nginx支持
二、大文件下载:
- 注意:使用readfile函数需要将php.ini的
memory_limit
设置大点(最好等于参数upload_max_filesize
),不能小于下载文件的大小,不然文件下载不动,这种方法需要占用内存,不宜用于大文件和很多人下载使用
if (!file_exists($file)) {
echo '文件不存在';
exit;
}
//可重命名为中文
setlocale(LC_ALL, "zh_CN.GBK");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
- 另外使用nginx的默认自带的XSendfile模块下载,该方法不通过PHP控制,交给nginx来处理 nginx配置,设置protected目录只允许nginx程序访问,防止直接从浏览器直接下载:
#禁止浏览器中访问,仅nginx内部访问(最好做别名alias,不然真实路径被屏蔽,php将无法对真实路径做任何操作,比如:判断文件是否存在、上传文件等等
location /protected/ {
internal;
alias $root_path/files/upload/src/
}
php代码
header("X-Accel-Redirect: /protected/test.pdf");
参考:http://www.lovelucy.info/x-sendfile-in-nginx.html