PHP实现上传和下载文件的操作

一、上传文件:

1、  php.ini配置: 找到 File Uploads 

    file_uploads = On    //打开上传文件的功能

    upload_tmp_dir  =  'd:/web/tmp'   ;   //上传文件的临时存储目录;取决于web服务器部署目录

    upload_max_filesize 3M;    //允许上传文件最大值,如若需要较大的值,则需先修改post方式的传输最大值

    post_max_size   =8M;

2、  .htaccess 配置

    属性和值之间用空格‘  ’隔开非等号‘=’:

adddefaultcharset utf-8     //设置默认字符  
php_value file_uploads On   //打开上传功能  
php_value post_max_size 6M   // post提交的最大值  
php_value upload_max_filesize 6M  //允许上传的最大值  

(一)上传单个文件:

        html 表单:

<form action="upload.php"  method="post" enctype="multipart/form-data">  
    <p><input type="file" name="ufile"></p>  
    <p><input type="submit" name="submit" value="上传"></p>  
</form>

        PHP接受处理上传文件 

扫描二维码关注公众号,回复: 1497367 查看本文章
//主要为move_uploaed_file() 的运用
if (!empty($_POST)) {  
        $dirName = "./".date("Y-m-d");  
        if (!is_dir($dirName)) {  
            mkdir($dirName);  //如无此目录则创建  
        }  
        $suffix = strrchr($_FILES['ufile']['name'], '.');//截取文件的后缀名  
        $url = $dirName.'/'.uniqid().$suffix;  //在日期的目录里以原来的后缀名以唯一性的文件名保存  
        $bool = move_uploaded_file($_FILES['ufile']['tmp_name'], $url); //从原来的临时文件移动到指定路径  
        if ($bool) {  
            echo "上传成功!";  
            exit();  
        }else{  
            echo "上传失败!";  
            exit();  
        }  
    } 

(二)上传多个文件:

<form action="upload.php"  method="post" enctype="multipart/form-data">
	<p><input type="file" name="ufile[]" multiple=""></p>
	<p><input type="submit" name="submit" value="上传"></p>
</form>
if(!empty($_POST)){
		//创建保存目录
		$dirName = "./".date('Y-m-d');
		if (!is_dir($dirName)) {
			mkdir($dirName);
		}
		foreach ($_FILES['ufile']['tmp_name'] as $key => $value) {
			//取文件后缀 ($key与$_FILES['ufile']['name']数组的key一致)
			$suffix = strrchr($_FILES['ufile']['name'][$key],'.');  
			//生成前缀
			$preffix = uniqid();
			//保存路径
			$url = $dirName."/".$preffix.$suffix;
			$bool = move_uploaded_file($value,$url);
		}
		if ($bool) {
			echo "上传成功!";
			exit();
		}else{
			echo "上传失败!";
			exit();
		}

	}

二、下载文件

    A. 当文件为浏览器不能识别的类型时,可直接用a标签实现下载 , 如:

<a href="../load/ay.xls">下载</a>  

    B.当文件为浏览器能识别的类型时,即如.html/.js/.css/.xml/.jpg/.jpeg等浏览器能解析直接打开的文件,可用header( ) 及file_get_contents( ) 实现,如: 

<a href="download.php">下载</a>
$filename = "./load/5b0bd336b7980.jpg";  
//提示浏览器为图片文件  
header('Content-type: image/jpeg');     
//Content-Disposition为内容处理方式,处理为附件,强制浏览器下载文件  
header('Content-Disposition: attachment; filename='.$filename);   
//将整个文件读入一个字符串,即将二进制对象转为utf-8编码  
echo file_get_contents($filename); 

    常见header( ) 响应头设置:

//定义编码  
header( 'Content-Type:text/html;charset=utf-8 ');  

//文档语言  
header('Content-language: en');  

//CSS  
header('Content-type: text/css');  
  
//Javascript  
header('Content-type: text/javascript');  
  
//JPEG Image  
header('Content-type: image/jpeg');  
  
//XML  
header('Content-type: text/xml'); 

//JSON  
header('Content-type: application/json');  
  
//PDF  
header('Content-type: application/pdf');  
  
//RSS  
header('Content-Type: application/rss+xml; charset=ISO-8859-1');  
  
//Text (Plain)  
header('Content-type: text/plain');  

//Atom  
header('Content-type: application/atom+xml'); 
 
 
//转到一个新地址  
header('Location: http://www.example.org/'); 

// ok  
header('HTTP/1.1 200 OK');  
  
//设置一个404头:  
header('HTTP/1.1 404 Not Found');  
  
//设置地址被永久的重定向  
header('HTTP/1.1 301 Moved Permanently');  
  
//文件延迟转向:  
header('Refresh: 10; url=http://www.example.org/');  
print 'You will be redirected in 10 seconds';  
  
//当然,也可以使用html语法实现  
// <meta http-equiv="refresh" content="10;http://www.example.org/ />  
  
// override X-Powered-By: PHP:  
header('X-Powered-By: PHP/4.4.0');  
header('X-Powered-By: Brain/0.6b');  
  
//告诉浏览器最后一次修改时间  
$time = time() - 60; // or filemtime($fn), etc  
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $time).' GMT');  
  
//告诉浏览器文档内容没有发生改变  
header('HTTP/1.1 304 Not Modified');  
  
//设置内容长度  
header('Content-Length: 1234');  
  
//设置为一个下载类型  
header('Content-Type: application/octet-stream');  
header('Content-Disposition: attachment; filename="example.zip"');  
header('Content-Transfer-Encoding: binary');  
// load the file to send:  
readfile('example.zip');  
  
// 对当前文档禁用缓存  
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');  
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past  
header('Pragma: no-cache');  
  
//设置内容类型:  
header('Content-Type: text/html; charset=iso-8859-1');  
header('Content-Type: text/html; charset=utf-8');  
header('Content-Type: text/plain'); //纯文本格式  
header('Content-Type: image/jpeg'); //JPG***  
header('Content-Type: application/zip'); // ZIP文件  
header('Content-Type: application/pdf'); // PDF文件  
header('Content-Type: audio/mpeg'); // 音频文件  
header('Content-Type: application/x-shockw**e-flash'); //Flash动画  
  
//显示登陆对话框  
header('HTTP/1.1 401 Unauthorized');  
header('WWW-Authenticate: Basic realm="Top Secret"');  
print 'Text that will be displayed if the user hits cancel or ';  
print 'enters wrong login data';  
//下载xlsx文件
$filename = rtrim($_SERVER['DOCUMENT_ROOT'],'/').'/app/files/payment_status.csv';  
header('Content-Disposition: attachment; filename=payment_status.xlsx');  
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');  
header('Content-Length: ' . filesize($filename));  
header('Content-Transfer-Encoding: binary');  
header('Cache-Control: must-revalidate');  
header('Pragma: public');  
readfile($filename);  


猜你喜欢

转载自blog.csdn.net/zhousulian/article/details/80494058