To enable file uploading on your intranet page, follow these steps:
Use the following HTML for file selection:
<input>
Update your JavaScript to send the selected file to the server:
$("#upload").on("click", function() { var file_data = $("#sortpicture").prop("files")[0]; var form_data = new FormData(); form_data.append("file", file_data); $.ajax({ url: "upload.php", // Point to the server-side PHP script dataType: 'text', // Expected response from PHP script cache: false, contentType: false, processData: false, data: form_data, type: 'post', success: function(php_script_response){ alert(php_script_response); // Display response from PHP script } }); });
Create a PHP script named upload.php to handle the file upload:
<?php if (0 < $_FILES['file']['error']) { echo 'Error: ' . $_FILES['file']['error'] . '<br>'; } else { move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']); } ?>
Ensure that the "uploads" directory has write permissions.
To rename the file during upload, use the following code in the PHP script:
move_uploaded_file( $_FILES['file']['tmp_name'], 'uploads/new_filename.extension' );
Remember to configure your PHP settings for upload_max_filesize and post_max_size accordingly.
The above is the detailed content of How to Upload Files Using jQuery AJAX and PHP?. For more information, please follow other related articles on the PHP Chinese website!