欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

php单个文件上传类codeguy/upload使用

程序员文章站 2022-04-30 12:58:16
...
注意:此扩展依赖于php的fileinfo扩展
mamp套件中已包含,只需在php.ini中添加一句
extension=php_fileinfo.dll,即可。
linux系统则:
yum install php-fileinfo
=================================
注意,上传相关配置
nginx
增加如下两行到nginx.conf的http{}段, 增大nginx上传文件大小限制
#设置允许发布内容为8M
client_max_body_size 8M;(说明,此参数可以放http段,也可以放server段,后者优先级高)

send_timeout    60;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;

====================================
php.ini
post_max_size = 8M
upload_max_filesize = 8M

另外,看情况设置
max_execution_time = 600 ;每个PHP页面运行的最大时间值(秒),默认30秒
max_input_time = 600 ;每个PHP页面接收数据所需的最大时间,默认60秒
memory_limit = 8m ;每个PHP页面所吃掉的最大内存,默认8M

==============================
php-fpm注意参数
request_terminate_timeout
request_slowlog_timeout
这两个参数如果设置过小的话会导致文件传输了一部分后连接关闭。

=============================
composer配置
"codeguy/upload":"1.3.2"


示例代码
<?php
require ("../vendor/autoload.php");

echo "<h1>上传demo</h1>";
if ($_SERVER['REQUEST_METHOD']=='GET') {
	echo <<<html
	<form method="POST" enctype="multipart/form-data">
	    <input type="file" name="foo" value=""/>
			<br><br><br>
	    <input type="submit" value="表单提交"/>
    </form>
html;
	exit;
} 

$storage = new \Upload\Storage\FileSystem(__DIR__."/upload");
if (count($_FILES)>0) {
	$keys = array_keys($_FILES);
	$form_file_name = $keys[0];
	$file = new \Upload\File($form_file_name, $storage);
}else {
	exit;
}


// Optionally you can rename the file on upload
$new_name=uniqid();
$file->setName($new_name);

// Validate file upload
// MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml
$file->addValidations(array(
		//You can also add multi mimetype validation
		new \Upload\Validation\Mimetype(array('image/png', 'image/gif', 'image/jpeg')),
		// Ensure file is no larger than 5M (use "B", "K", M", or "G")
		new \Upload\Validation\Size('5M'),
));

// Try to upload file
try {
	// Success!
	$file->upload();
	echo "upload success,新文件名:".$file->getNameWithExtension();
} catch (\Exception $e) {
	// Fail!
	$errors = $file->getErrors();
	echo $errors[0];
}
相关标签: upload php