首先还是系统的环境
下面正式开始
- 先安装 Apache和PHP
sudo apt-get update
sudo apt-get install apache2 php libapache2-mod-php
- 创建一个存放图片的目录并且设置权限
sudo mkdir /var/www/html/images
sudo chmod -R 777 /var/www/html/images
- 编辑 Apache 配置文件
sudo nano /etc/apache2/sites-available/000-default.conf
将下面代码放在下边
Alias /images /var/www/html/images
<Directory /var/www/html/images>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
</Directory>
- 重启 Apache
sudo service apache2 restart
- 创建一个网页用于上传图片当然这里你可以自己写一个漂亮的页面
sudo nano /var/www/html/upload.html
鼠标右键将下面的代码粘贴,ctrl+o保存,ctrl+x退出
<html>
<meta charset="UTF-8">
<body>
<form method="post" enctype="multipart/form-data" action="upload.php">
<label for="file">选择要上传的文件:</label>
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="上传" />
</form>
</body>
</html>
- 创建一个PHP脚本来支持上传图片
sudo nano /var/www/html/upload.php
将下面的代码粘贴保存
<?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
// 检测文件是否是图片
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
echo "<h1>文件不是图片。</h1>";
$uploadOk = 0;
}
}
// 检测文件是否已存在
if (file_exists($target_file)) {
echo "<h1>文件已存在。</h1>";
$uploadOk = 0;
}
// 上传文件
if ($uploadOk == 0) {
echo "<h1>上传失败。</h1>";
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "<h1>文件". basename( $_FILES["file"]["name"]). "已成功上传。</h1>";
} else {
echo "<h1>上传失败。</h1>";
}
}
?>
- 再创建一个网页来显示和访问上传的图片
sudo nano /var/www/html/images.php
将下面的代码粘贴保存
<?php
$dir_path = "images/";
$extensions = array('jpg', 'jpeg', 'png','gif');
$files = array();
if ($handle = opendir($dir_path)) {
while (false !== ($file = readdir($handle))) {
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($extension, $extensions)) {
$files[] = $file;
}
}
closedir($handle);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>图片上传和下载</title>
</head>
<body>
<h1>上传图片</h1>
<form method="post" enctype="multipart/form-data" action="upload.php">
<input type="file" name="file">
<input type="submit" name="submit" value="上传">
</form>
<h1>所有图片列表</h1>
<?php foreach ($files as $file) { ?>
<p>
<a href="<?php echo $dir_path . $file ?>">
<img src="<?php echo $dir_path . $file ?>" style="max-height:150px;">
</a>
<br>
<a href="<?php echo $dir_path . $file ?>"><?php echo $file ?></a>
</p>
<?php } ?>
</body>
</html>
使用http://树莓派IP地址/upload.html是上传
使用http://树莓派IP地址/images/是图片的列表
使用http://树莓派IP地址/images/图片名称就是图片大图