写一个MVC上传照片功能
时间: 2024-05-01 07:20:58 浏览: 17
好的,下面是一个简单的MVC上传照片功能的示例代码。
Model层代码:
```php
class PhotoModel {
public function savePhoto($file) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($file["name"]);
move_uploaded_file($file["tmp_name"], $target_file);
return $target_file;
}
}
```
Controller层代码:
```php
class PhotoController {
public function uploadPhoto() {
$model = new PhotoModel();
if(isset($_POST["submit"])) {
$file = $_FILES["fileToUpload"];
$target_file = $model->savePhoto($file);
$view = new PhotoView();
$view->showPhoto($target_file);
}
}
}
```
View层代码:
```php
class PhotoView {
public function showPhoto($target_file) {
echo "<img src='$target_file' alt='uploaded photo'>";
}
}
```
在HTML表单中添加文件上传控件:
```html
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
```
当用户上传照片后,控制器会调用模型层的`savePhoto`方法,将照片保存到服务器上,并返回文件的路径。然后,控制器会调用视图层的`showPhoto`方法,将照片显示在网页上。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)