Yii框架中AJAX请求指定控制器方法遇404错误的解决问询
Let's break down the issues causing your 404 error and fix them step by step:
1. Critical: Fix Controller Action Naming
In Yii, all controller action methods must start with the action prefix for the framework to recognize them as routable endpoints. Your current method name UploadMusicFile doesn't follow this rule, so Yii can't map it to a valid route. Rename it to:
public function actionUploadMusicFile(){ // Your existing code here }
2. Generate the Correct URL for Module Controller
Your controller is located in the post module (protected/humhub/modules/post/controllers/PostController.php), so you need to include the module ID in your route when generating the URL. You also had mixed Yii 1 and Yii 2 syntax in your view—here's how to fix it for both versions:
For Yii 2.x
Use the module ID (post), controller ID (post, lowercase version of PostController), and action ID (kebab-case upload-music-file or camelCase uploadMusicFile both work):
var url = '<?php echo Yii::$app->urlManager->createUrl(['post/post/upload-music-file']); ?>';
For Yii 1.x
If you're actually using Yii 1 (your view had Yii::app() calls), use this consistent syntax instead:
var url = '<?php echo Yii::app()->createUrl('post/post/uploadMusicFile'); ?>';
3. Fix Frontend AJAX Code Issues
Your current code has a return false; before the $.ajax() call, which means the AJAX request never runs! Also, file uploads require proper FormData handling:
function uploadImage(){ // Correct URL (adjust for Yii 1/2 as above) var url = '<?php echo Yii::$app->urlManager->createUrl(['post/post/upload-music-file']); ?>'; // Create FormData object to handle file uploads var formData = new FormData(); formData.append('file', $('input[type="file"]')[0].files[0]); $.ajax({ url: url, method: 'POST', data: formData, dataType: 'json', // Auto-parses JSON response, no need for $.parseJSON contentType: false, processData: false, success:function(data){ console.log("Upload success:", data); }, error:function(xhr, status, error){ console.log("Upload error:", status, error); } }); // Move return false here to prevent default form submission (if needed) return false; }
4. Fix Backend File Upload Handling
Your backend code had issues with file access and insecure database queries—here's a cleaned-up, secure version:
public function actionUploadMusicFile(){ // Use Yii's built-in UploadedFile helper for safe file handling $uploadedFile = \yii\web\UploadedFile::getInstanceByName('file'); if($uploadedFile){ $target_dir = "/home/jmwglobaladmin/public_html/melmory/uploads/music_memory/"; // Ensure the upload directory exists (create if not) if(!is_dir($target_dir)){ mkdir($target_dir, 0755, true); } $target_file = $target_dir . basename($uploadedFile->name); if($uploadedFile->saveAs($target_file)){ // Get latest post ID safely with query builder $latestPost = Yii::$app->db->createCommand( 'SELECT id FROM post ORDER BY id DESC LIMIT 1' )->queryOne(); $new_id = $latestPost ? $latestPost['id'] + 1 : 1; // Insert to database with parameter binding to avoid SQL injection Yii::$app->db->createCommand()->insert('memory_music', [ 'post_id' => $new_id, 'memory_music' => $uploadedFile->name // Use original filename or custom name ])->execute(); // Return structured JSON response Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return ['status' => 'success', 'message' => 'File uploaded successfully']; } else { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return ['status' => 'error', 'message' => 'Failed to save file']; } } else { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return ['status' => 'error', 'message' => 'No file selected']; } }
内容的提问来源于stack exchange,提问作者Jahan Ahmed Abbasi

