网站实现上传下载文件

网站实现上传文件功能

使用目录跳转到你想去的地方

前言:

想将云服务器当作云盘来使用,极简。 wordpress一键部署的网站 总共三步:前端文件download.html,后端文件upload.php,目录名images。

下方举例用的“示例图片.jpg”,记得修改为你自己放进去的文件。非浏览器可显示的文件可以把download属性删掉,算是稍微简化一下。

1、前端代码(HTML + JavaScript)

download.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>文件上传和下载</title>
</head>
<body>
    <h1>上传文件</h1>
    <input type="file" id="fileUpload" accept=".pdf, .doc, .docx, .txt, .md, .html, .zip, .rar, .mp4, .mp3, .jpg, .jpeg, .png">
    <button onclick="uploadFile()">上传</button>
    <h1>下载文件</h1>
    <a href="/images/示例图片.jpg" download="示例图片.jpg">jk少女</a><br><br>
    <script>
        function uploadFile() {
            var fileInput = document.getElementById('fileUpload');
            var file = fileInput.files[0];
            var formData = new FormData();
            formData.append('file', file);
            fetch('/upload.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => console.log(data))
            .catch(error => console.error(error));
        }
    </script>
</body>
</html>

2、后端代码(PHP)

upload.php

<?php
if(isset($_FILES['file'])){
    $file = $_FILES['file'];
    $fileName = $file['name'];
    $fileTmpName = $file['tmp_name'];
    $fileSize = $file['size'];
    $fileError = $file['error'];
    $fileType = $file['type'];
    $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
    
    // 检查文件类型和大小
    if ($fileError === UPLOAD_ERR_OK && $fileSize > 0 && is_string($fileExt)) {
        // 将文件从临时目录移动到目标目录(这里是images目录)
        move_uploaded_file($fileTmpName, 'images/' . $fileName);
        echo '文件上传成功!';
    } else {
        echo '文件类型或大小不正确!';
    }
} else {
    echo '没有选择文件!';
}
?>

3、在同目录下建一个images文件夹用来存放文件

访问网址后面添加/download.html,示例:

https://ip地址/download.html

有什么好点子欢迎大家交流,互相学习

完善:

2023.12.30遍历文件名


使用的时候才察觉到无法显示目录下的文件内容,我不可能每次上传文件后都去手动添加一条下载链接;

添加了背景图片,同时添加文字背景以不被背景色干扰;

1、在服务器上创建一个list_files.php文件,该文件应该返回一个JSON格式的字符串,其中包含/images目录下的所有文件名。以下是你可以参考的list_files.php代码:

<?php
$files = scandir('/images');
$files = array_diff($files, array('.', '..'));
echo json_encode(array_values($files));
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>文件上传和下载</title>
    <!--添加文字背景-->
    <style>
        #fileList a {
            background-color: white;
            padding: 1px;
        }
    </style>
</head>
<body background="/images/背景2.jpg" style="background-size:100%;background-attachment: fixed;">
    <h1>上传文件</h1>
    <input type="file" id="fileUpload" accept=".pdf, .doc, .docx, .txt, .md, .html, .zip, .rar, .mp4, .mp3, .jpg, .jpeg, .png">
    <button onclick="uploadFile()">上传</button>
    <h1>下载文件</h1>
    <div id="fileList"></div>

    <script>
        function uploadFile() {
            var fileInput = document.getElementById('fileUpload');
            var file = fileInput.files[0];
            var formData = new FormData();
            formData.append('file', file);
            fetch('/upload.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => console.log(data))
            .catch(error => console.error(error));
        }

        function listFiles() {
            fetch('/list_files.php')
            .then(response => response.json())
            .then(data => {
                var fileList = document.getElementById('fileList');
                fileList.innerHTML = '';
                data.forEach(function(file) {
                    var link = document.createElement('a');
                    link.href = '/images/' + file;
                    link.download = file;
                    link.innerHTML = file;
                    fileList.appendChild(link);
                    fileList.appendChild(document.createElement('br'));
                });
            })
            .catch(error => console.error(error));
        }

        listFiles();
    </script>
</body>
</html>

emm,背景和文字背景暂时有点鸡肋,有没有什么其它功能和我交流交流呀

2024.1.8更新

download.html把第30行的目录修改为自己的

<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="utf-8">
  <title>文件上传和下载</title>

  <style>
    #fileList a {
      background-color: white;
      padding: 1px;
    }
    
    .viewButton {
      background-color: #4CAF50;
      border: none;
      color: white;
      padding: 5px 10px;
      text-align: center;
      text-decoration: none;
      display: inline-block;
      font-size: 16px;
      margin: 4px 2px;
      cursor: pointer;
    }
  </style>

</head>

<body background="/images/芙莉莲.jpg" style="background-size:100%;background-attachment: fixed;">

  <h1 style="color:white;">上传文件</h1>
  
  <input type="file" id="fileUpload">
  <button onclick="uploadFile()">上传</button>
  <span id="progress"></span>
  
    <br>
    <a href="/showimage.php">
        <button>只想要看图片?</button>
    </a>
  
  <h1 style="color:white;">下载文件</h1>
  
  <div id="fileList"></div>

  <script>
    function uploadFile() {
      // 上传文件JS代码
        var fileInput = document.getElementById('fileUpload');
        var file = fileInput.files[0];

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/upload.php');

        xhr.upload.onprogress = function(event) {
            var percent = Math.round(event.loaded / event.total * 100);
            document.getElementById('progress').textContent = percent + '%';
        };

        var formData = new FormData();
        formData.append('file', file);

        xhr.send(formData);

        xhr.onload = function() {
            document.getElementById('progress').textContent = '上传完成';
        };
    }
    
    function listFiles() {
      // 列出文件JS代码 
        fetch('/list_files.php')
        .then(response => response.json())
        .then(data => {
            var fileList = document.getElementById('fileList');
            fileList.innerHTML = '';
            data.forEach(function(file) {
                var link = document.createElement('a');
                link.href = '/images/' + file;
                link.download = file;
            link.innerHTML = file;
                fileList.appendChild(link);
                if (file.endsWith('.mp4') || file.endsWith('.mp3')) {
                    var viewButton = document.createElement('button');
                    viewButton.innerHTML = '查看';
                    viewButton.className = 'viewButton';
                    viewButton.onclick = function() {
                        window.open('/images/' + file);
                    };
                    fileList.appendChild(viewButton);
                }
                fileList.appendChild(document.createElement('br'));
            });
        })
        .catch(error => console.error(error));
    }

    listFiles();
  </script>

</body>

</html>

list_files.php里修改目录为自己的:
 

<?php
$files = scandir('/www/wwwroot/hgoipwhjf.com/images');
$files = array_diff($files, array('.', '..'));
echo json_encode(array_values($files));
?>

upload.php:
 

<?php   

$allowedTypes = ['jpg','jpeg','png','gif','mp4','mov','pdf','doc','txt']; 

$maxSize = 500 * 1024 * 1024;  

if(isset($_FILES['file'])){

    $file = $_FILES['file'];
        
    $fileName = $file['name'];
  
    $fileTmpName = $file['tmp_name'];

    $fileSize = $file['size'];

    echo "接收到文件: " . basename($fileName) . ",大小:{$fileSize} Bytes";
    
    $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    if (!in_array($fileExt, $allowedTypes)) {
        echo "文件类型不允许!";
        return;
    }
    
    if($fileSize > $maxSize) {
        echo "文件大小超过限制!";
        return; 
    }
        
    $uploadFile = 'images/' . $fileName;
    
    if(move_uploaded_file($fileTmpName, $uploadFile)) {
       echo $uploadFile . " 上传成功!";
    } else {
       echo "文件保存失败!";
    }
     
} else {
    echo "没有选择文件!";
}

?>

showimage.php:
 

<!DOCTYPE html>
<html>
<head>
  <title>图片展示</title>
  
  <style>
    .img-thumb {
      width: 150px;
      height: 150px;
      object-fit: cover;
    }
    
    .img-large {
      width: 50%;
      height: auto;
    }
  </style>
  
  <script>
    function goBack() {
    window.history.back(); 
  }
    function enlargeImg(img) {
      img.className = "img-large";
    } 
    function toggleImg(img) {
  if(img.className == "img-thumb") {
    img.className = "img-large";
  } else {
    img.className = "img-thumb";
  }
}
  </script>
  
</head>

<body>
    <button onclick="goBack()">返回首页</button>

<div class="image-container"> 

  <?php
  header("Cache-Control: max-age=604800");
    $dir = 'images/';
    $images = glob($dir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

    foreach ($images as $image) {
  echo '<img class="img-thumb" onclick="toggleImg(this)" src="' . $image . '">'; 
}
  ?>

</div>

</body>
</html>

免责声明

注意:此代码示例仅用于演示目的,并可能存在安全风险。在实际应用中,您需要添加更多的安全验证和检查来防止潜在的攻击。

  • 18
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
为了实现C++的FastDFS上传和下载,需要使用FastDFS C客户端API。以下是实现FastDFS上传和下载的步骤: 1.安装FastDFS C客户端API 可以从FastDFS官方网站下载FastDFS C客户端API。下载后,将其解压缩并安装。 2.上传文件 使用FastDFS C客户端API上传文件的步骤如下: ```c++ #include "fastdfs_client.h" #include "fastdfs_client_ex.h" int main(int argc, char *argv[]) { char *conf_filename = "/etc/fdfs/client.conf"; char *local_filename = "/path/to/local/file"; char group_name[FDFS_GROUP_NAME_MAX_LEN + 1]; char remote_filename[4096]; ConnectionInfo *pTrackerServer; int result; int64_t file_size; FDFSFileInfo file_info; // 初始化FastDFS客户端 if ((result = fdfs_client_init(conf_filename)) != 0) { return result; } // 获取Tracker服务器 pTrackerServer = tracker_get_connection(); if (pTrackerServer == NULL) { fdfs_client_destroy(); return errno != 0 ? errno : ECONNREFUSED; } // 上传文件 result = fdfs_upload_by_filename(pTrackerServer, NULL, local_filename, NULL, 0, remote_filename, sizeof(remote_filename)); if (result != 0) { printf("upload file fail, error no: %d, error info: %s\n", result, STRERROR(result)); tracker_disconnect_server_ex(pTrackerServer, true); fdfs_client_destroy(); return result; } // 获取上传文件的信息 result = fdfs_get_file_info_ex(pTrackerServer, NULL, remote_filename, strlen(remote_filename), &file_info); if (result != 0) { printf("get file info fail, error no: %d, error info: %s\n", result, STRERROR(result)); tracker_disconnect_server_ex(pTrackerServer, true); fdfs_client_destroy(); return result; } // 打印上传文件的信息 printf("group name: %s\n", file_info.group_name); printf("remote filename: %s\n", file_info.filename); printf("file size: %ld\n", file_info.file_size); printf("create time: %s\n", formatDatetime(file_info.create_timestamp, "%Y-%m-%d %H:%M:%S", NULL, 0)); printf("source ip address: %s\n", file_info.source_ip_addr); // 断开Tracker服务器连接 tracker_disconnect_server_ex(pTrackerServer, true); // 销毁FastDFS客户端 fdfs_client_destroy(); return 0; } ``` 3.下载文件 使用FastDFS C客户端API下载文件的步骤如下: ```c++ #include "fastdfs_client.h" #include "fastdfs_client_ex.h" int main(int argc, char *argv[]) { char *conf_filename = "/etc/fdfs/client.conf"; char *local_filename = "/path/to/local/file"; char group_name[FDFS_GROUP_NAME_MAX_LEN + 1]; char remote_filename[4096]; ConnectionInfo *pTrackerServer; int result; int64_t file_size; FDFSFileInfo file_info; // 初始化FastDFS客户端 if ((result = fdfs_client_init(conf_filename)) != 0) { return result; } // 获取Tracker服务器 pTrackerServer = tracker_get_connection(); if (pTrackerServer == NULL) { fdfs_client_destroy(); return errno != 0 ? errno : ECONNREFUSED; } // 下载文件 result = fdfs_download_file_ex(pTrackerServer, NULL, remote_filename, strlen(remote_filename), 0, &file_size, local_filename); if (result != 0) { printf("download file fail, error no: %d, error info: %s\n", result, STRERROR(result)); tracker_disconnect_server_ex(pTrackerServer, true); fdfs_client_destroy(); return result; } // 断开Tracker服务器连接 tracker_disconnect_server_ex(pTrackerServer, true); // 销毁FastDFS客户端 fdfs_client_destroy(); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值