温馨提示×

ubuntu js如何实现文件上传

小樊
46
2025-10-12 06:55:16
栏目: 编程语言

在Ubuntu环境下使用JavaScript实现文件上传,通常涉及前端和后端的配合。以下是一个基本的示例,展示如何使用HTML、JavaScript(前端)和Node.js与Express框架(后端)来实现文件上传功能。

步骤一:搭建Node.js服务器

首先,确保你已经在Ubuntu系统上安装了Node.jsnpm(Node包管理器)。如果尚未安装,可以参考以下命令进行安装:

sudo apt update
sudo apt install nodejs npm

1.1 创建项目目录并初始化

mkdir file-upload-demo
cd file-upload-demo
npm init -y

1.2 安装必要的依赖

我们将使用express作为服务器框架,multer作为处理multipart/form-data的中间件。

npm install express multer

1.3 创建服务器文件

创建一个名为server.js的文件,并添加以下代码:

const express = require('express');
const multer  = require('multer');
const path = require('path');

const app = express();

// 设置存储引擎
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/') // 文件将被保存到uploads目录
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname) // 重命名文件以避免冲突
  }
});

// 初始化上传
const upload = multer({
  storage: storage,
  limits: { fileSize: 10 * 1024 * 1024 }, // 限制文件大小为10MB
  fileFilter: function (req, file, cb) {
    checkFileType(file, cb);
  }
}).single('file'); // 'file'是表单中文件字段的名称

// 检查文件类型
function checkFileType(file, cb) {
  // 允许的文件扩展名
  const filetypes = /jpeg|jpg|png|gif/;
  // 检查扩展名
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  // 检查MIME类型
  const mimetype = filetypes.test(file.mimetype);

  if (mimetype && extname) {
    return cb(null, true);
  } else {
    cb('Error: Images Only!');
  }
}

// 创建uploads目录(如果不存在)
const fs = require('fs');
const uploadsDir = './uploads';
if (!fs.existsSync(uploadsDir)){
  fs.mkdirSync(uploadsDir);
}

// 设置静态文件目录
app.use(express.static('public'));

// 路由处理
app.post('/upload', (req, res) => {
  upload(req, res, (err) => {
    if (err) {
      res.status(400).send({ message: err });
    } else {
      if (req.file == undefined) {
        res.status(400).send({ message: 'No file selected!' });
      } else {
        res.send({
          message: 'File uploaded!',
          file: `uploads/${req.file.filename}`
        });
      }
    }
  });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

1.4 运行服务器

在终端中运行以下命令启动服务器:

node server.js

服务器将监听3000端口。

步骤二:创建前端页面

在项目根目录下创建一个名为public的文件夹,并在其中创建一个HTML文件index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>文件上传示例</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 50px;
    }
    .upload-container {
      max-width: 500px;
      margin: auto;
    }
    input[type="file"] {
      margin-top: 20px;
    }
    button {
      padding: 10px 20px;
      margin-top: 10px;
    }
    .message {
      margin-top: 20px;
      text-align: center;
    }
  </style>
</head>
<body>
  <div class="upload-container">
    <h2>上传文件</h2>
    <form id="uploadForm" action="/upload" method="POST" enctype="multipart/form-data">
      <input type="file" name="file" accept="image/*" required>
      <button type="submit">上传</button>
    </form>
    <div class="message" id="message"></div>
  </div>

  <script>
    document.getElementById('uploadForm').addEventListener('submit', function(e) {
      e.preventDefault();
      const form = this;
      const formData = new FormData(form);

      fetch('/upload', {
        method: 'POST',
        body: formData
      })
      .then(response => response.json())
      .then(data => {
        if (data.message) {
          document.getElementById('message').innerText = data.message;
          // 可选:显示上传的文件图片
          const img = document.createElement('img');
          img.src = data.file;
          img.width = 300;
          document.getElementById('message').appendChild(img);
        }
      })
      .catch(error => {
        console.error('Error:', error);
        document.getElementById('message').innerText = '上传失败';
      });
    });
  </script>
</body>
</html>

2.1 说明

  • 表单设置enctype="multipart/form-data"用于文件上传,name="file"需与后端upload(req, res, callback)中的字段名一致。
  • 前端验证:简单的前端验证,确保用户选择了文件。
  • Fetch API:使用Fetch API将表单数据异步发送到服务器,并处理响应。

步骤三:测试文件上传

  1. 确保Node.js服务器正在运行:

    node server.js
    
  2. 在浏览器中打开http://localhost:3000,你将看到文件上传页面。

  3. 选择一个图片文件并点击“上传”按钮。如果一切正常,服务器会将文件保存到uploads/目录,并在页面上显示上传成功的消息及图片预览。

可选:增强功能

  • 多文件上传:修改后端代码以支持多文件上传,并相应调整前端表单和JavaScript代码。
  • 文件类型和大小限制:根据需求调整multer的配置,限制允许的文件类型和大小。
  • 用户界面优化:使用CSS框架如Bootstrap美化上传界面。
  • 错误处理:增强前后端的错误处理机制,提供更友好的用户反馈。

使用其他前端框架

如果你更喜欢使用前端框架如React、Vue.js或Angular,也可以在这些框架中实现类似的文件上传功能。关键在于使用适当的HTTP客户端(如Axios)将文件发送到后端API。

示例:使用React进行文件上传

3.1 创建React应用

npx create-react-app file-upload-react
cd file-upload-react
npm start

3.2 修改App.js

import React, { useState } from 'react';
import axios from 'axios';

function App() {
  const [file, setFile] = useState(null);
  const [message, setMessage] = useState('');

  const handleFileChange = (e) => {
    setFile(e.target.files[0]);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('file', file);

    axios.post('http://localhost:3000/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    .then(response => {
      setMessage(response.data.message);
      if (response.data.file) {
        const img = document.createElement('img');
        img.src = response.data.file;
        img.width = 300;
        document.getElementById('message').appendChild(img);
      }
    })
    .catch(error => {
      console.error('Error:', error);
      setMessage('上传失败');
    });
  };

  return (
    <div className="App">
      <h2>上传文件</h2>
      <form onSubmit={handleSubmit}>
        <input type="file" onChange={handleFileChange} required />
        <button type="submit">上传</button>
      </form>
      <div id="message" className="message">{message}</div>
    </div>
  );
}

export default App;

3.3 安装Axios

npm install axios

3.4 运行React应用

确保Node.js服务器正在运行,然后在React项目目录中启动React应用:

npm start

访问http://localhost:3000,你将看到React实现的文件上传界面。

总结

以上示例展示了如何在Ubuntu环境下使用JavaScript(前端)和Node.js与Express框架(后端)实现基本的文件上传功能。根据具体需求,你可以扩展和优化此基础示例,例如添加用户认证、文件存储优化、进度条显示等功能。

0