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

为处理input file的AJAX请求附加额外变量并修改imgauth的src

Complete Code for File Preview & AJAX Upload with Extra Variable

Here's the full, polished code that meets both your requirements—previewing the selected image in imgauth and sending the name variable along with the file via AJAX:

$('#inpfile').change(function() {
    // Get the extra variable from the select element
    var name = $('#selauth').val();
    // Get the selected file
    var file_data = $('#inpfile').prop('files')[0];
    
    // Only proceed if a file is selected
    if (file_data) {
        // 1. Update imgauth src to preview the image
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#imgauth').attr('src', e.target.result);
        };
        reader.readAsDataURL(file_data);
        
        // 2. Prepare FormData with both file and extra variable
        var form_data = new FormData();
        form_data.append('inpfile', file_data);
        form_data.append('name', name); // Add the extra variable here
        
        // 3. Complete AJAX request
        $.ajax({
            url: "authors-pro-img-from-disc.php",
            type: 'post',
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            success: function(response) {
                // Handle successful upload (e.g., show success message, update UI)
                console.log('Upload successful:', response);
                // Optional: Reset the file input if needed
                $('#inpfile').val('');
            },
            error: function(xhr, status, error) {
                // Handle upload errors (e.g., show error message)
                console.error('Upload failed:', error);
            }
        });
    }
});

Key Additions Explained:

  • Image Preview: We use FileReader to convert the selected file into a data URL, which we then set as the src attribute of #imgauth. This lets users see the image immediately after selecting it.
  • Extra Variable: Added form_data.append('name', name); to include the name value from #selauth in the FormData sent to your PHP script. On the server side, you can access this via $_POST['name'].
  • Completion of AJAX Options: Added the data property (to pass the FormData), plus success and error handlers to handle the server response and any potential issues gracefully.
  • File Check: Added a check for file_data to avoid running code if no file was selected.

Notes for Your PHP Script (authors-pro-img-from-disc.php):

You can access the uploaded file via $_FILES['inpfile'] and the extra variable via $_POST['name'] just like you would with a regular form submission.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:34:59