使用php上传文件时显示下载链接并强制下载文档

时间:2016-07-29 10:08:24

标签: php css

我在互联网上找到了关于如何使用php创建上传表单的教程。虽然它非常好并且解释得很好,但我需要添加一些额外的功能,这就是我需要你帮助的原因。

    <?php
require 'config.php';

if (isset ( $_SERVER ['REQUEST_METHOD'] ) == 'POST') {
 // when submit button is clicked
 if (isset ( $_POST ['submit'] )) {
  // get user's data
  $name = $_POST ['name'];
  $email = $_POST ['email'];
  $images = "";

  // check if user has added images
  if(strlen(($_FILES ['upload'] ['tmp_name'] [0])) != 0){
   $upload_dir = "images/";

   // move all uploaded images in directory
   for ($i = 0; $i < count($_FILES['upload']['name']); $i++) {
    $ext = substr(strrchr($_FILES['upload']['name'][$i], "."), 1);

    // generate a random new file name to avoid name conflict
    $fPath = md5(rand() * time()) . ".$ext";
    $images .= $fPath.";";

    $result = move_uploaded_file($_FILES['upload']['tmp_name'][$i], $upload_dir . $fPath);
   } 
  }else {
   // if user doesn't have any images, add default value
   $images .= "no images";
  }

  // write the user's data in database
  // prepare the query
  $query = "INSERT INTO users(name, email,images) VALUES
  ('$name', '$email','$images')";

  // TODO check if the user's informations are successfully added
  // in the database
  $result = mysql_query ( $query ); 
 }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>Upload File/s</title>
 <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<!-- form container -->
 <div id="form">
  <form action="" name="form1" method="POST" enctype="multipart/form-data">
   <input name="name" type="text" id="name" value="name" />
   <input name="email" type="email" id="email" value="example@test.com" />
   <div class="upload">
          <input type="file" name="upload[]" id="upload" multiple/>
      </div>
   <Button id="save" name="submit" type="submit" value="submit">Upload and Save</Button>
  </form>
 </div>
</body>
</html>

上传文件时,不会显示下载链接,并且文件在上传时具有随机名称。我现在想要的是显示下载链接并使文件(pdf,png,jpg和其他图像类型)强制下载,而不是显示在另一个选项卡上。如果可能的话,我希望文件在上传时保持相同的文件名。

提前致谢。

1 个答案:

答案 0 :(得分:0)

您的脚本会在$ image变量中保存要下载的网址。首先在全局范围内创建图像变量:

<?php
$images="";
//rest

现在您可以随处访问它。所以你可以在你的html中回应它

<div id="response">
<?php
//get every single image in an array
$img=explode(";",$images);
if($img[0]=="no images"){
echo "no uploads yet";
}else{
echo "<a href='images/". $img[1]."' download>Download</a>";
}
?>
</div>