如何添加一个简单的图像上传功能

How do I add a simple image upload feature?

本文关键字:图像 功能 简单 何添加 添加 一个      更新时间:2023-09-26

我想给我的新网站一个功能,我可以通过按钮上传一张图片,并将图片存储(本地存储)在另一个.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