5.3 文件上传
本来是没有这个功能的,当我尝试使用将图片以二进制文件存储到数据库的方法时,发现图片能存入数据库,该图片也能查看,但是却无法在网页中显示,因为解决不能该显示图片的问题,所以我尝试通过上传文件(图片)的方式,将图片存储到该管理系统的某目录下,而数据库中则存储该路径的文本信息,网页显示图片时,图片只需要链接到该路径即可。
该功能主要利用表单提交数据和php后端代码实现。
相关代码:
获取表单提交的图片,并将其存储到某目录下:
//限制上传的文件为图片
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
//echo $_FILES["file"]["size"];
$extension = end($temp); // 获取文件后缀名
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 2048000) //限制图片小于2mb
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "错误:: " . $_FILES["file"]["error"] . "<br>";
}
else
{
// 判断当前目录下的 upload 目录是否存在该文件
if (file_exists("../../upload/" . $_FILES["file"]["name"]))
{
//echo $_FILES["file"]["name"] . " 文件已经存在。 ";
//就继续使用原来的文件
}
else
{
// 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
move_uploaded_file($_FILES["file"]["tmp_name"], "../../upload/" . $_FILES["file"]["name"]);
}
}
}
获取该图片的路径:
//取得上传后的图片的相对路径,可将其拼接到对应的SQL语句
$zpn=$_FILES["file"]["name"];
$zp=sprintf("%s%s/%s",dirname(dirname(dirname($_SERVER["PHP_SELF"]))),"/upload",$zpn);
————————————————
版权声明:本文为优快云博主「想当探险家的提莫」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/weixin_45766049/article/details/117746319
此时选择了图片但未上传,就能预览该图片
相关代码:
// 获取图片预览地址函数
function getObjectURL(file) {
var url = null;
if (window.createObjectURL!=undefined) {
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
function uploader(e){
// 将图片信息通过getObjectURL函数处理出预览地址
var s = getObjectURL(e[0]);
// 获取img元素,label元素,div[上传按钮]元素
var img=document.getElementById(‘o_photo_img’);
// 设置图片展示样式
img.style.padding=‘3px’;
img.style.borderStyle=‘solid’;
img.style.borderColor=‘#eee’;
img.style.borderWidth=‘1px’;
// 设置img的src值实现图片预览
img.src=s;
}
————————————————
版权声明:本文为优快云博主「想当探险家的提莫」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/weixin_45766049/article/details/117746319
https://bytes.com/topic/php/insights/740327-uploading-files-into-mysql-database-using-php
阶段0:建立资料库
数据库很简单。 一个表,带有用于文件数据的BLOB字段,而几个字段用于与文件有关的各种信息:
CREATE TABLE file
(
id
Int Unsigned Not Null Auto_Increment,
name
VarChar(255) Not Null Default ‘Untitled.txt’,
mime
VarChar(50) Not Null Default ‘text/plain’,
size
BigInt Unsigned Not Null Default 0,
data
MediumBlob Not Null,
created
DateTime Not Null,
PRIMARY KEY (id
)
)
如您所见,我们存储文件名,包括扩展名。
我们有mime类型,用于让浏览器知道我们正在处理哪种文件。
文件大小,以字节为单位。
最后是数据本身,位于MediumBlob字段中。
阶段1:上传文件
现在,我们需要从用户那里获取文件。 我们设计的表不需要用户提供任何其他信息,因此我们将使其变得简单,并创建一个HTML表单,其中仅包含一个“文件”输入字段和一个提交按钮:
请注意元素的第三个属性“ enctype”。 这告诉浏览器如何将表单数据发送到服务器。 就这样,在发送文件时,必须将其设置为“ multipart / form-data”。 如果以其他任何方式设置或根本没有设置,则可能无法正确传输文件。
在底部,我们有一个指向第3阶段创建的列表的链接。
阶段2:将文件添加到数据库
在第1阶段构建的表单中,我们将action属性设置为“ add_file.php”。 这是我们在流程的此阶段要构建的文件。
此文件需要检查文件是否已上传,确保已上传且没有错误,然后将其添加到数据库中:
<?php // Check if a file has been uploaded if(isset($_FILES['uploaded_file'])) { // Make sure the file was sent without errors if($_FILES['uploaded_file']['error'] == 0) { // Connect to the database $dbLink = new mysqli('127.0.0.1', 'user', 'pwd', 'myTable'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Gather all required data $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']); $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']); $data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name'])); $size = intval($_FILES['uploaded_file']['size']); // Create the SQL query $query = " INSERT INTO `file` ( `name`, `mime`, `size`, `data`, `created` ) VALUES ( '{$name}', '{$mime}', {$size}, '{$data}', NOW() )"; // Execute the query $result = $dbLink->query($query); // Check if it was successfull if($result) { echo 'Success! Your file was successfully added!'; } else { echo 'Error! Failed to insert the file' . "{$dbLink->error}"; } } else { echo 'An error accured while the file was being uploaded. ' . 'Error code: '. intval($_FILES['uploaded_file']['error']); } // Close the mysql connection $dbLink->close(); } else { echo 'Error! A file was not sent!'; } // Echo a link back to the main page echo '
Click here to go back
'; ?>阶段3:列出所有现有文件
因此,现在我们的数据库中有几个文件,我们需要创建文件列表并链接它们,以便可以下载它们:
There are no files in the database
'; } else { // Print the top of a table echo ''; // Print each file while($row = $result->fetch_assoc()) { echo "Name | Mime | Size (bytes) | Created | |
{$row['name']} | {$row['mime']} | {$row['size']} | {$row['created']} |
阶段4:下载文件
这部分通常是最容易引起混乱的部分。
要真正了解其工作原理,您必须了解浏览器如何下载文件。 当浏览器从HTTP服务器请求文件时,服务器响应将包含有关其确切包含内容的信息。 这些信息位称为标头。 标头通常包含有关发送的数据类型,响应的大小以及文件名的信息。
当然还有很多其他标题,在这里我将不介绍它们,但是值得研究!
现在,这段代码。 我们仅从读取阶段3中的链接发送的ID开始。如果ID有效,我们将在接收到的ID的文件上获取信息,发送标题,最后发送文件数据:
<?php // Make sure an ID was passed if(isset($_GET['id'])) { // Get the ID $id = intval($_GET['id']); // Make sure the ID is in fact a valid ID if($id <= 0) { die('The ID is invalid!'); } else { // Connect to the database $dbLink = new mysqli('127.0.0.1', 'user', 'pwd', 'myTable'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Fetch the file information $query = " SELECT `mime`, `name`, `size`, `data` FROM `file` WHERE `id` = {$id}"; $result = $dbLink->query($query); if($result) { // Make sure the result is valid if($result->num_rows == 1) { // Get the row $row = mysqli_fetch_assoc($result); // Print headers header("Content-Type: ". $row['mime']); header("Content-Length: ". $row['size']); header("Content-Disposition: attachment; filename=". $row['name']); // Print data echo $row['data']; } else { echo 'Error! No image exists with that ID.'; } // Free the mysqli resources @mysqli_free_result($result); } else { echo "Error! Query failed:{$dbLink->error}"; } @mysqli_close($dbLink); } } else { echo 'Error! No ID was passed.'; } ?>
任何体面的浏览器都应该能够读取标题并了解该文件是什么类型的文件以及要下载的文件而不是打开文件。 终点线
因此,正如您所看到的,这并不像人们想象的那么复杂。