如何添加一个简单的图像上传功能
How do I add a simple image upload feature?
我想给我的新网站一个功能,我可以通过按钮上传一张图片,并将图片存储(本地存储)在另一个.html
页面上,然后如果我获取了它的绝对URL,我可以将其发布在论坛网站上,那里会显示预览,到目前为止,我有一个功能可以上传和预览图片。。但我想更上一层楼。
HTML:
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
Javascript:
<script>
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
previewFile(); //calls the function named previewFile()
</script>
摘要:上传图像,将其存储(本地存储),然后获取其绝对URL,将其粘贴到另一个网站上,以获得该图像的预览。
第1部分:上传
将文件上传到PHP很容易。为了给用户提供选项,你必须在HTML表单中添加一个文件输入
<input type="file" name="picture" />
为了确保PHP接收到文件,必须将表单方法设置为POST,将enctype设置为multipart/form-data-
<form action="receiver.php" method="POST" enctype="multipart/form-data">
如果你想通过javascript上传,你可能需要使用AJAX。下面是一个例子:https://stackoverflow.com/a/6960586/3797667
第2部分:接收(receiver.php)
上传的文件可以通过$_FILES[]
访问。这里有一个例子:
if(isset($_FILES['image'])){//Checks if file is set
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
//(above) checks file extension by getting text after last dot
$expensions= array("jpeg","jpg","png");//supported file types
if(in_array($file_ext,$expensions)=== false){//is the extension in the supported types
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){//PHP only supports files under 2MB
$errors[]='File size must be excately 2 MB';
}
//If there's no error moves files to folder "images" in the root of this file, else prints all the errors
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
有关文件管理的更多方法,请查看此链接:http://php.net/manual/en/ref.filesystem.php
第3部分:访问
如果你想获得文件的URL,你可能想查看这篇文章:PHP动态获取将包含在其他文件中的特定文件的完整绝对URL路径
如果你觉得你需要更多信息,请在下面评论,我会更新帖子。祝你的项目好运!
来源:
http://www.tutorialspoint.com/php/php_file_uploading.htm
相关文章:
- 为图像滑块jquery添加项目符号功能
- 使用JavaScript功能切换图像位置
- 单击水平滚动库中的图像以居中显示无法工作的功能
- AngularJS:为ng-repeat中的图像添加切换功能
- 如何在保持鼠标悬停功能的同时居中跨过图像
- 这个图像加载功能有什么作用
- 图像上传功能将++(+1)副本添加到下一次上传.出了什么问题或如何重置“选定图像”
- 将复选框转换为图像,需要添加拖动功能才能更改图像
- 本地存储功能中的图像不起作用
- 利用移动设备上的滑动功能浏览图像阵列
- jQuery预加载图像功能
- 点击时输入图像功能打开,再次点击功能关闭
- 单击时动画化图像功能,同时重叠其同级元素
- HTML5 画布绘制图像功能在源画布和目标画布相同时变慢
- 具有ajax的一次更改图像功能已经完成
- 禁用幻灯片放映插件中的居中图像功能
- 动态画布绘制图像功能
- 开发3D交互图像功能的方向是什么?
- 如何在Gmail和Google Chrome 12+中使用剪贴板粘贴图像功能
- 双击图像功能