UploadFile
公司網站需要用到,找不到好的套件只好自行開發囉
Form表單的寫法
html的架構大致上是以下這樣
<div class="form-group col-md-12">
<label for="fileToUpload" class="">檔案上傳:</label>
<div class="">
<input type="file" name="fileToUpload" id="fileToUpload" class="form-control">
<p class="help-block">只能上傳tar.gz, .rar, .zip格式的檔案</p>
</div>
</div>
PHP會做一個API
// 存取路徑
$target_dir = "file/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// 檢查上傳的檔案是否為真的
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
$uploadOk = 0;
}
// 檢查檔案是否已經存在
if (file_exists($target_file)) {
echo "Sorry, file already exists."."<br />";
$uploadOk = 0;
}
// 檢查檔案大小
if ($_FILES["fileToUpload"]["size"] > 15*1024*1024) {
echo "Sorry, your file is too large."."<br />";
$uploadOk = 0;
}
// 檢查檔案副檔名是否符合要求
if($imageFileType != "tar.gz" && $imageFileType != "rar" && $imageFileType != "zip" ) {
echo "Sorry, only tar.gz, .rar, .zip files are allowed."."<br />";
$uploadOk = 0;
}
// 回報錯誤或是回報上傳成功或是有其他未知的錯誤
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded."."<br />";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."."<br />";
$uploadOk = 1;
} else {
echo "Sorry, there was an error uploading your file."."<br />";
}
}
Last updated
Was this helpful?