一、上傳
1、thinkphp
<div id="content">
<p>上傳圖片</p>
<form method="post" action="__CONTROLLER__/upload" enctype="multipart/form-data">
<input class="input1" type="file" name="file1">
<input class="input2" type="submit" value="確定" />
</form>
<if condition="$all['path'] neq ''">
<br/><img src="__ROOT__{$all['path']}" height="100">
<form action="__CONTROLLER__/download/id/{$all['id']}"><input type="submit" value="下載"/></form>
<else />
<br/>暫無圖片
</if>
</div>
實現效果是:上傳完圖片直接顯示出來
當前控制器下的upload方法:
public function upload(){
$myblog=D('photo');
if (IS_POST){
if($_FILES['file1']['tmp_name']!=''){
$upload=new \Think\Upload();
$upload->maxSize = 20000;//文件大小的最大值
$upload->exts = array('jpg', 'jpeg');//文件的類型
$upload->savePath = './Public/Uploads/';
$upload->rootPath = './';
$info = $upload->uploadOne($_FILES['file1']);
if(!$info){
$this->error($upload->getError());
}else{
$path=$info['savepath'].$info['savename'];
$data['path']=$path;
$data['name']=$info['savename'];
$myblog->add($data);
header("Location:".__CONTROLLER__."/index");//跳轉,相當於刷新本頁面
}
}
}
}
2、php
aa.php:
<html>
<body>
<form action="upl.php" method="post"
enctype="multipart/form-data">
<label for="file">上傳:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="確定" />
</form>
<?php
if(file_exists("upload/1.jpg")){
echo '<img src="upload/1.jpg"></img>';
}
?>
</body>
</html>
upl.php:
<?php
if (($_FILES["file"]["type"] == "image/jpg")||($_FILES["file"]["type"] == "image/jpeg")&& ($_FILES["file"]["size"] < 20000)){
if ($_FILES["file"]["error"] > 0){
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
header("Location:aa.php");
}
}
}
else
{
echo "Invalid file";
}
?>
二、下載
1、thinkphp
<form action="__CONTROLLER__/download"><input type="submit" value="下載"/></form>
當前控制器的download方法:
public function download(){
$path="D:/WampServer/wamp64/www/a/myblog/Public/resume.txt";//文件的路徑
$http=new \Org\Net\Http();
$http->download($path);
}
2、php
<form action="download.php"><input type="submit" value="下載"/></form>
download.php:
<?php
/**
* 文件下載
*
**/
header("Content-type:text/html;charset=utf-8");
download('upload/resume.txt', 'resume.txt');
function download($file, $down_name){//文件路徑,文件名
//判斷給定的文件存在與否
if(!file_exists($file)){
die("您要下載的文件已不存在,可能是被刪除");
}
$fp = fopen($file,"r");
$file_size = filesize($file);
//下載文件需要用到的頭
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length:".$file_size);
header("Content-Disposition: attachment; filename=".$down_name);
$buffer = 1024;
$file_count = 0;
//向瀏覽器返回數據
while(!feof($fp) && $file_count < $file_size){
$file_con = fread($fp,$buffer);
$file_count += $buffer;
echo $file_con;
}
fclose($fp);
}
?>