本文最后更新于 2024-12-05,文章内容可能已经过时。

1、修改Nginx的配置文件,增加如下代码

location /upload/ {
    alias /var/www/uploads/; # 指定存储路径
    dav_methods PUT;
    create_full_put_path on; # 自动创建目录
    client_max_body_size 100M; # 最大文件大小限制
}

2、生成以下Html文件并放在Nginx的html目录下

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>文件上传</title>
    <script src="https://unpkg.com/vue@3"></script>
    <script src="https://unpkg.com/naive-ui"></script>
    <script src="https://cdn.tailwindcss.com"></script>
  </head>
  <body class="bg-gray-100 flex justify-center items-center h-screen">
    <div id="app"></div>

    <script>
      const { createApp, ref } = Vue;
      const { NCard, NUpload, NButton, NProgress } = naive;

      const App = {
        setup() {
          const fileList = ref([]); // 已选文件列表
          const uploading = ref(false);
          const uploadProgress = ref(0);

          // 上传文件到后端
          const handleUpload = async (file) => {
            uploading.value = true;
            uploadProgress.value = 0;

            const formData = new FormData();
            formData.append("file", file);

            try {
              const response = await fetch("/upload/" + file.name, {
                method: "PUT",
                body: formData,
              });

              if (response.ok) {
                alert("文件上传成功!");
              } else {
                alert("文件上传失败!");
              }
            } catch (error) {
              alert("网络错误,文件上传失败!");
            } finally {
              uploading.value = false;
            }
          };

          // 文件选择变化时触发上传
          const handleChange = ({ file }) => {
            handleUpload(file);
          };

          return {
            fileList,
            uploading,
            uploadProgress,
            handleChange,
          };
        },
        template: `
        <div class="max-w-lg w-full p-5 bg-white rounded-lg shadow-lg">
          <n-card title="文件上传" bordered>
            <n-upload
              v-model:file-list="fileList"
              :on-change="handleChange"
              :disabled="uploading"
              :max="1"
              show-file-list
            >
              <n-button>选择文件</n-button>
            </n-upload>
            <div v-if="uploading" class="mt-4">
              <n-progress :percentage="uploadProgress" height="10" />
            </div>
          </n-card>
        </div>
      `,
      };

      createApp(App).use(naive).mount("#app");
    </script>
  </body>
</html>

注意以上await fetch后面的upload要与第一步location后边的upload相对应,相等。

3、通过浏览器访问该html文件即可将文件直接上传到Nginx所在服务器中