为处理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
FileReaderto convert the selected file into a data URL, which we then set as thesrcattribute of#imgauth. This lets users see the image immediately after selecting it. - Extra Variable: Added
form_data.append('name', name);to include thenamevalue from#selauthin the FormData sent to your PHP script. On the server side, you can access this via$_POST['name']. - Completion of AJAX Options: Added the
dataproperty (to pass the FormData), plussuccessanderrorhandlers to handle the server response and any potential issues gracefully. - File Check: Added a check for
file_datato 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
相关产品推荐
相关产品推荐

