萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery Form Plugin ajaxSubmit 非同步上傳圖片並同步儲存表單資料完整實戰

核心依賴

<script src="jquery-1.9.0.js"></script>
<script src="jquery.form.js"></script> <!-- 關鍵插件 -->

HTML 表單 (multipart/form-data)

<form id="uploadImgForm" action="${ctx}/upload/upload.do" method="post" enctype="multipart/form-data">
    <div class="control-group">
        <label class="control-label">*商圈名:</label>
        <div class="controls">
            <input type="text" name="businessName" maxlength="20" id="businessName" />
            <input type="hidden" name="userId" value="${userId}" />
        </div>
    </div>
    <div class="control-group">
        <label class="control-label">*商圈 Logo:</label>
        <div class="controls">
            <input type="file" name="file" id="file" />
        </div>
    </div>
    <div class="control-group">
        <label class="control-label">*商圈英文名:</label>
        <div class="controls">
            <input type="text" name="businessEname" id="businessEname" />
        </div>
    </div>
    <div class="form-actions">
        <button type="button" id="imgSave" class="btn btn-primary">提交註冊</button>
    </div>
</form>

前端驗證與提交邏輯

$(document).ready(function() {
    // 即時驗證
    $('#businessName, #businessEname').blur(function() {
        var $this = $(this), $err = $('#' + this.id + '_error');
        if ($this.val()) $err.html("<img src='success.gif'>");
        else $err.addClass('error_div').html("<img src='error.gif'> 不能為空");
    });

    // 提交
    $('#imgSave').click(function() {
        // 前端驗證
        var ok = true;
        $('#businessName, #businessEname, #file').each(function() {
            if (!$(this).val()) {
                $('#' + this.id + '_error').addClass('error_div').html("<img src='error.gif'> 必填");
                ok = false;
            }
        });
        if (!ok) return;

        // 檢查副檔名
        var ext = $('#file').val().split('.').pop().toLowerCase();
        if (!['jpg','jpeg','gif','bmp','png'].includes(ext)) {
            $('#file_error').addClass('error_div').html("<img src='error.gif'> 格式不支援");
            return;
        }

        // ajaxSubmit 核心
        $('#uploadImgForm').ajaxSubmit({
            type: 'POST',
            dataType: 'json',
            beforeSubmit: function() {
                $('#imgSave').prop('disabled', true).text('上傳中...');
            },
            success: function(result) {
                if (result.success) {
                    alert('註冊成功!');
                    location.href = '${ctx}/business/list';
                } else {
                    alert('失敗: ' + result.msg);
                }
            },
            error: function(xhr) {
                alert('系統錯誤: ' + xhr.status);
            },
            complete: function() {
                $('#imgSave').prop('disabled', false).text('提交註冊');
            }
        });
    });
});

後端處理重點 (Spring MVC 範例)

@Controller
@RequestMapping("/upload")
public class UploadController {
    @PostMapping("/upload.do")
    @ResponseBody
    public Map upload(
            @RequestParam("businessName") String businessName,
            @RequestParam("businessEname") String businessEname,
            @RequestParam("userId") Long userId,
            @RequestParam("file") MultipartFile file) {

        Map result = new HashMap<>();
        try {
            // 1. 驗證檔案
            if (file.isEmpty()) { result.put("success", false); result.put("msg", "檔案為空"); return result; }

            // 2. 儲存檔案 (生成唯一檔名、驗證 MIME、掃毒...)
            String original = file.getOriginalFilename();
            String ext = FilenameUtils.getExtension(original).toLowerCase();
            String newName = UUID.randomUUID() + "." + ext;
            Path dest = Paths.get(uploadDir, newName);
            Files.copy(file.getInputStream(), dest);

            // 3. 存入資料庫
            Business biz = new Business();
            biz.setName(businessName);
            biz.setEname(businessEname);
            biz.setLogoUrl("/uploads/" + newName);
            biz.setUserId(userId);
            businessService.save(biz);

            result.put("success", true);
        } catch (Exception e) {
            log.error("上傳失敗", e);
            result.put("success", false); result.put("msg", "伺服器錯誤");
        }
        return result;
    }
}

關鍵技術點總結

關鍵點說明
enctype="multipart/form-data"表單必須設定,否則檔案不會上傳
jquery.form.js自動將 FormData 序列化並處理 iframe/ XHR2 相容
ajaxSubmit()一鍵提交表單含檔案,支援進度事件 uploadProgress
前端驗證必填、副檔名、檔案大小 (可用 file.size HTML5 File API)
後端 MultipartResolverSpring 需配置 CommonsMultipartResolver 或 StandardServletMultipartResolver
安全性檔案類型驗證 (MIME + 副檔名)、重新命名、存儲路徑非 Web 可直接訪問、病毒掃描

現代替代:原生 Fetch + FormData

document.getElementById('imgSave').addEventListener('click', async () => {
    const form = document.getElementById('uploadImgForm');
    const formData = new FormData(form); // 自動收集所有欄位含檔案
    // 可追加額外欄位
    // formData.append('extra', 'value');

    const btn = this;
    btn.disabled = true; btn.textContent = '上傳中...';

    try {
        const resp = await fetch(form.action, { method: 'POST', body: formData, credentials: 'include' });
        const result = await resp.json();
        if (result.success) { alert('成功'); location.href = '${ctx}/business/list'; }
        else alert('失敗: ' + result.msg);
    } catch (e) { alert('異常: ' + e); }
    finally { btn.disabled = false; btn.textContent = '提交註冊'; }
});

零依賴、原生支援進度事件 (xhr.upload.onprogress)、程式碼更簡潔。

copyright © 萬盛學電腦網 all rights reserved