作者:陈业贵 华为云享专家 51cto(专家博主 明日之星 TOP红人) 阿里云专家博主

文章目录


先上传后下载哦我使用的是phpstudy
请在www目录下创建一个uploads文件夹

代码

<?php
$link=mysqli_connect('localhost','root','root','a');//链接数据库(数据库软件账号密码都是root.数据库是a)
//然后是指定php链接数据库的字符集
mysqli_set_charset($link,'utf8');//字符串utf8
$file=dirname(__FILE__);
$file1=str_replace('\\', '/',$file);//获取绝对路径D:/phpstudy_pro/WWW
foreach($_FILES as $file){//遍历传过来的两个及以上的文件
$fileNum=count($file['name']);

for ($i=0; $i < $fileNum; $i++) {

$file3="/uploads/".$file['name'][$i];//获取路径
$today = date();//获取日期
echo move_uploaded_file($_FILES['file']['tmp_name'][$i],$file1.$file3);

$sql = "INSERT INTO upload(name,time,path)
VALUES ('{$file['name'][$i]}','{$today}','{$file3}')";//插入到数据库中
mysqli_query($link,$sql);//运行


}

echo json_encode(["code"=>200,"msg"=>'保存成功',"data"=>$file['name']]);//显示


}

效果

PHP案例:下载文件(特色:只能下载上传的文件哦))_开发语言

PHP案例:下载文件(特色:只能下载上传的文件哦))_php_02

代码

<?php

$request = $_FILES['file'];//获取传上来的文件
$dl = $request['name'];//获取文件
$file=dirname(__FILE__);
$path=str_replace('\\', '/',$file)."/uploads/";//获取绝对路径D:/phpstudy_pro/WWW/uploads/



if ($dl != "" && is_file($path.$dl)) {//如果文件没有名字的话。或者不是下载指定目录下的话,return 0;
header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename= ".$path.$dl);
header("Content-Transfer-Encoding: binary");
header("Connection: Keep-Alive");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: public");
header("Content-Length: " . filesize($path.$dl));//文件大小
readfile($path.$dl);//读取文件
exit;
}

效果:

PHP案例:下载文件(特色:只能下载上传的文件哦))_mysql_03