1. 程式人生 > 其它 >1 檔案上傳

1 檔案上傳

1.1 機制

當上傳一個檔案時,會先將其作為臨時目錄傳到伺服器,如果不將其啟動到其它目錄,就會刪除。

1.2 需要使用的東西

<form action="upload.php" method="post"

enctype="multipart/form-data">

<input type="file"

l 在表單裡寫個輸入型別為file

l 還需要新增enctype="multipart/form-data"

詳情查手冊:POST方法上傳

上傳的表單介面

<!DOCTYPE html>

<html lang="zh-cn">

<head>

<meta charset="UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>上傳檔案</title>

</head>

<body>

<form action="upload.php" method="post" enctype="multipart/form-data">

使用者名稱:<input type="text" name="uName"><br />

<!-- 對於瀏覽器的建議,設定檔案大小 -->

<input type="hidden" name="MAX_FILE_SIZE" value="30000">

檔案:<input type="file" name="img">

<input type="submit" value="提交">

</form>

</body>

</html>

php上傳後端:upload.php

<?php

$uName =$_POST['uName'];

echo $uName.'<br/>';

//1.首先判斷是否出錯

if($_FILES['userfile']['error'] > 0){

switch($_FILES['userfile']['error']){

case 1:

die('上傳檔案超過了php.ini中upload_max_filesize選項限制的值。');

case 2:

die('上傳檔案的大小超過了 HTML 表單中 MAX_FILE_SIZE 選項指定的值。');

case 3:

die('檔案只有部分被上傳。');

case 4:

die('檔案沒有被上傳');

case 6:

die('找不到臨時檔案');

case 7:

die('檔案寫入失敗');

}

}

//2.判斷上傳型別是否符合規定

echo $_FILES['userfile']['type'];

$type = array('image/jpeg','image/png','image/gif');//允許的格式

if(!in_array($_FILES['userfile']['type'],$type)){

die('別給我亂傳東西。');

}

//3.判斷所傳檔案大小是否在運許之內

$size = 300000;

if($_FILES['userfile']['size'] > $size){

die('檔案過大,別搞啊。');

}

//4.製作上傳的目錄

$uploaddir = 'D:/phpstudy/phpstudy_pro/WWW/test/檔案上傳例項/upload';

if(!file_exists($uploaddir)){

mkdir($uploaddir);

}

//5.重新命名檔案

//(1)先獲取字尾名,突然感覺我不想這麼做

//$suffix = strrchr($_FILES['userfile']['name'],'.');

do{

$name = md5(time()).$_FILES['userfile']['name'];

}while(file_exists($uploaddir.'/'.$name));

//6.移動檔案

echo $name;

if(move_uploaded_file($_FILES['userfile']["tmp_name"],$uploaddir.'/'.$name)){

echo "上傳成功。";

}else{

echo "上傳失敗";

}

?>