如何在不重新加载页面的情况下发送带有文件的表单?

问题描述 投票:0回答:1
ajax spring
1个回答
0
投票

要使用 AJAX 发送带有文件的表单而不重新加载页面,您需要使用

FormData
来正确处理文件上传。

<form id="settings" method="POST" enctype="multipart/form-data">
    <!-- Other form fields -->
    <input type="file" id="logo" name="logo" accept="image/png, image/jpeg, image/gif">
    <button type="submit" id="send" class="btn btn-primary">Save</button>
</form>
$(document).ready(function() {
    $('#settings').submit(function(e){
        e.preventDefault();
        
        var formData = new FormData(this);
        
        $.ajax({
            url: '/settings',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            cache: false,
            success: function(response){
                alert('Form submitted successfully!');
                // Handle the response from the server
            },
            error: function(){
                console.log('Error occurred!');
            }
        });
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.