一、客户端配置
表单页面
表单的发送方式:post
enctype=”multipart/form-data”
二、服务端配置
$_FILES中保存的上传文件信息
name 上传文件的名称
type 上传文件的类型
tmp-name 上传到服务器上的临时文件名
size 文件大小
error 错误信息
$filename = $_FILES['pic']['name'];
file_uploads = On 上传开关
upload_tmp_dir 临时文件保存的目录
upload_max_filesize 允许上传文件的最大值
max_file_uploads 允许一次上传的最大文件数
post_max_siez post方式发送数据的最大值
max_execution_time = -1 设置了脚本被解析器终止之前允许的最大执行时间,单位为秒,防止程序写的不好而占尽服务器资源
max_input_time = 60 脚本解析输入数据允许的最大时间,单位秒
max_input_nesting_level = 64 设置输入变量的嵌套深度
memory_limit = 128M 最大单线程的独立内存使用量
max_input_vars = 1000 接受多少输入的变量
三、错误信息说明
UPLOAD_ERR_OK 值为0,没有错误发生,上传成功
UPLOAD_ERR_INI_SIZE 值为1 上传的文件超过了php.ini中upload_max_filesize选项限制的值
UPLOAD_ERR_FORM_SIZE 值为2 上传文件的大小超过了hmtl表单中max_file_size选项指定的值
UPLOAD_ERR_PARTIAL 值为3 文件只有部分被上传
UPLOAD_ERR_NO_FILE 值为4 没有文件被上传
UPLOAD_ERR_NO_TMP_DIR 值为6 找不到临时文件
UPLOAD_ERR_CANT_WRITE 值为7 文件写入失败
UPLOAD_ERR_EXTENSION 值为8 上传的文件被PHP扩展程序中断
五、简单实例
//1.上传图片名称
$filename = $_FILES['pic']['name'];
//2.获得文件后缀
$ext = substr($filename,strrpos($filename,'.')+1);
//3.重命名
$filename = date('YmdHis').mt_rand(1000,9999).'.'.$ext;
//4.获得临时文件
$tmpName = $_FILES['pic']['tmp_name'];
//5 报错
$error = $_FILES['pic']['error'];
if($error==0){
//方法一 move_uploaded_file($tmpName,'../uploads/'.$filename);
//方法二
copy($tmpName,'../uploads/'.$filename);
}
文件下载
$mime_types = array(
"pdf" => "application/pdf",
"txt" => "text/plain",
"html" => "text/html",
"htm" => "text/html",
"zip" => "application/zip",
"doc" => "application/msword",
"docx" => "application/msword",
"xls" => "application/vnd.ms-excel",
"xlsx" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"pptx" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"png" => "image/png",
"jpeg" => "image/jpg",
"jpg" => "image/jpg",
);
$ext = substr($filename, strrpos($filename, '.') + 1);
if ($filename !== '') {
$content_type = array_key_exists($ext, $mime_types) ? $mime_types[$ext] : "application/force-download";
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, pre-check=0");
header("Content-Disposition: attachment; filename=" . basename($filename) . "");
header("Content-Type: " . $content_type . ",charset=utf-8");
header("Content-Transfer-Encoding: binary");
//header("Content-Length: " . filesize($filename));
ob_clean();
flush();
readfile($filename);
exit;
} else {
exit('下载失败', '');
}