我在互联网上找到了一个关于如何在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 );
}
}
?>
这个脚本总体上做得非常好,但唯一的问题是,当我上传图像文件或pdf时,它们会在新标签中打开,但它们不会下载。如何在单击下载链接时自动下载上载的图像文件?提前谢谢。
答案 0 :(得分:0)
添加下载链接,如下所示
<a href="link/to/your/download/image" download>Download link</a>
在apache config
中添加以下代码<Location "/images">
<Files *.*>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>
</Location>