You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap模态框文件上传并发送至邮箱的实现方法问询

实现Bootstrap模态窗口中上传文件发送至邮箱的功能

问题描述

我有一个集成文件上传功能的Bootstrap模态窗口,窗口内设有「发送至邮箱」按钮,想编写函数实现将已上传的文件发送到指定邮箱。

现有代码

HTML部分

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  打开模态窗口
</button>

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-fullscreen-lg-down">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">模态窗口标题</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="file-loading">
          <input id="input-b9" name="input-b9[]" multiple type="file">
        </div>
        <div id="kartik-file-errors"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary" id="sendEmailBtn">发送至邮箱</button>
      </div>
    </div>
  </div>
</div>

JavaScript部分

$(document).ready(function() {
    $("#input-b9").fileinput({
        showPreview: false,
        showUpload: false,
        elErrorContainer: '#kartik-file-errors',
        allowedFileExtensions: ["pdf", "doc", "docx"]
    });
});

完整实现方案

1. 前端逻辑修改

给「发送至邮箱」按钮绑定点击事件,获取选中文件并通过AJAX发送到后端接口:

$(document).ready(function() {
    $("#input-b9").fileinput({
        showPreview: false,
        showUpload: false,
        elErrorContainer: '#kartik-file-errors',
        allowedFileExtensions: ["pdf", "doc", "docx"]
    });

    // 绑定发送邮件按钮点击事件
    $("#sendEmailBtn").click(function() {
        // 获取选中的文件列表
        const selectedFiles = $("#input-b9").fileinput('getFileStack');
        if (selectedFiles.length === 0) {
            alert("请先选择要发送的文件");
            return;
        }

        // 创建FormData对象封装文件与参数
        const formData = new FormData();
        selectedFiles.forEach(file => {
            formData.append('files[]', file);
        });
        // 添加目标邮箱(可根据需求改为用户输入框获取)
        formData.append('targetEmail', 'recipient@example.com');

        // 发送AJAX请求到后端
        $.ajax({
            url: '/api/send-email-with-attachments', // 后端接口地址
            type: 'POST',
            data: formData,
            processData: false, // 禁止自动处理数据
            contentType: false, // 禁止自动设置Content-Type
            success: function(res) {
                alert("文件已成功发送至邮箱");
                $("#exampleModal").modal('hide');
                $("#input-b9").fileinput('clear'); // 清空文件选择
            },
            error: function(xhr) {
                alert(`发送失败:${xhr.responseText || '未知错误'}`);
            }
        });
    });
});

2. 后端处理示例(PHP)

前端无法直接发送邮件,必须通过后端服务实现。以下是基于PHPMailer的示例,需先通过Composer安装依赖:composer require phpmailer/phpmailer

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

// 接收前端参数
$targetEmail = $_POST['targetEmail'] ?? '';
$uploadedFiles = $_FILES['files'] ?? [];

// 参数验证
if (empty($targetEmail) || !filter_var($targetEmail, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo "无效的邮箱地址";
    exit;
}
if (empty($uploadedFiles['name'])) {
    http_response_code(400);
    echo "未选择任何文件";
    exit;
}

// 初始化邮件发送实例
$mail = new PHPMailer(true);
try {
    // SMTP服务器配置(以QQ邮箱为例)
    $mail->isSMTP();
    $mail->Host = 'smtp.qq.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your-qq-email@qq.com'; // 发件人邮箱
    $mail->Password = 'your-authorization-code'; // 邮箱授权码(非登录密码)
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port = 465;

    // 设置发件人与收件人
    $mail->setFrom('your-qq-email@qq.com', '文件发送系统');
    $mail->addAddress($targetEmail);

    // 添加附件
    $allowedExts = ['pdf', 'doc', 'docx'];
    for ($i = 0; $i < count($uploadedFiles['name']); $i++) {
        if ($uploadedFiles['error'][$i] === UPLOAD_ERR_OK) {
            $fileExt = strtolower(pathinfo($uploadedFiles['name'][$i], PATHINFO_EXTENSION));
            if (in_array($fileExt, $allowedExts)) {
                $mail->addAttachment($uploadedFiles['tmp_name'][$i], $uploadedFiles['name'][$i]);
            }
        }
    }

    // 设置邮件内容
    $mail->isHTML(true);
    $mail->Subject = '您收到一份上传文件';
    $mail->Body = '<p>您好,这是通过上传系统发送的文件,请查收附件。</p>';
    $mail->AltBody = '您好,这是通过上传系统发送的文件,请查收附件。';

    $mail->send();
    echo "邮件发送成功";
} catch (Exception $e) {
    http_response_code(500);
    echo "邮件发送失败:" . $mail->ErrorInfo;
}

// 清理临时文件
foreach ($uploadedFiles['tmp_name'] as $tmpFile) {
    if (file_exists($tmpFile)) {
        unlink($tmpFile);
    }
}
?>

关键注意事项

  • 前端:通过fileinput插件的getFileStack方法获取选中文件,用FormData保证文件能正确传输。
  • 后端:必须配置合法的SMTP服务器(不同邮箱的SMTP地址、端口、授权方式不同),同时要二次验证文件扩展名,防止恶意文件上传。
  • 大文件处理:若需支持大文件上传,需修改PHP配置中的upload_max_filesize、post_max_size、max_execution_time等参数。

内容的提问来源于stack exchange,提问作者PineappleBros

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 11:30:53