C# WPF中使用RestSharp通过PHP API上传MP4视频失败求助
Hey there! Let's walk through how to get that MP4 upload working with RestSharp and your PHP API. I've helped folks troubleshoot this exact issue before, so let's break it down step by step.
1. Correct RestSharp Upload Code (C# WPF)
First, let's make sure your C# code is set up properly for multipart file uploads — this is the standard way to send files over HTTP with RestSharp. Here's a tested example:
using RestSharp; using System.Windows; // Inside your WPF button click handler or async method private async void UploadVideoButton_Click(object sender, RoutedEventArgs e) { // Replace with your actual API endpoint var client = new RestClient("https://your-server-domain.com/upload.php"); var request = new RestRequest(Method.Post); // Optional: Add any required auth headers if your API uses them request.AddHeader("Authorization", "Bearer your-api-token-here"); try { // Add the MP4 file — critical: the first parameter ("video_file") must match what your PHP API expects request.AddFile( parameterName: "video_file", path: @"C:\Users\YourUser\Videos\sample.mp4", contentType: "video/mp4" ); // Add any extra form fields your API needs (like a video title) request.AddParameter("video_title", "My Awesome WPF Upload"); // Execute the request asynchronously (better for WPF to avoid freezing the UI) var response = await client.ExecuteAsync(request); if (response.IsSuccessful) { MessageBox.Show($"Upload success! Server response: {response.Content}"); } else { // This is key for debugging — even failed responses often have clues from the server MessageBox.Show($"Upload failed.\nStatus: {response.StatusCode}\nServer message: {response.Content}"); } } catch (Exception ex) { MessageBox.Show($"Error during upload: {ex.Message}\nStack trace: {ex.StackTrace}"); } }
Key Notes for C# Code:
- Parameter Name Match: The first argument in
AddFile("video_file") must exactly match the field name your PHP code uses to receive the file. If they don't line up, PHP won't see the file at all. - MIME Type: Specifying
"video/mp4"helps the server recognize the file type — some servers reject files without a valid content type. - Async Execution: Using
ExecuteAsyncprevents your WPF UI from freezing during the upload, especially for large videos.
2. PHP API Server Side Setup
Next, let's ensure your PHP endpoint is correctly configured to receive and save the file. Here's a robust example with error handling:
<?php // Define your upload directory — make sure it exists and has write permissions $uploadDirectory = './uploaded_videos/'; // Create directory if it doesn't exist if (!is_dir($uploadDirectory)) { mkdir($uploadDirectory, 0755, true); } // Check if the file was sent correctly if (!isset($_FILES['video_file'])) { echo json_encode([ 'status' => 'error', 'message' => 'No file received — check your request parameter name' ]); exit; } $file = $_FILES['video_file']; // Handle upload errors if ($file['error'] !== UPLOAD_ERR_OK) { $errorMessages = [ UPLOAD_ERR_INI_SIZE => 'File exceeds upload_max_filesize limit in php.ini', UPLOAD_ERR_FORM_SIZE => 'File exceeds MAX_FILE_SIZE set in the request', UPLOAD_ERR_PARTIAL => 'File was only partially uploaded', UPLOAD_ERR_NO_FILE => 'No file was selected for upload', UPLOAD_ERR_NO_TMP_DIR => 'Server missing temporary upload directory', UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk — check directory permissions', UPLOAD_ERR_EXTENSION => 'File upload blocked by server extension' ]; $errorMsg = $errorMessages[$file['error']] ?? 'Unknown upload error'; echo json_encode(['status' => 'error', 'message' => $errorMsg]); exit; } // Generate a safe filename to avoid overwrites $safeFileName = uniqid() . '_' . basename($file['name']); $targetPath = $uploadDirectory . $safeFileName; // Move the temporary file to the final directory if (move_uploaded_file($file['tmp_name'], $targetPath)) { echo json_encode([ 'status' => 'success', 'message' => 'File uploaded successfully', 'file_path' => $targetPath ]); } else { echo json_encode(['status' => 'error', 'message' => 'Failed to move uploaded file — check directory permissions']); } ?>
Key Notes for PHP Code:
- Permissions: The
uploaded_videosdirectory needs write permissions (usechmod 0755 uploaded_videos/on Linux, or right-click > Properties > Security on Windows servers). - PHP.ini Limits: Check your server's
php.inifile and increase these values if needed:upload_max_filesize = 64M(or larger for big videos)post_max_size = 64M(must be at least as big asupload_max_filesize)
- Error Feedback: The code returns clear JSON error messages — this lets your WPF app know exactly what went wrong.
3. Common Troubleshooting Steps
If you're still having issues, check these common pitfalls:
- Mismatched Parameter Names: Double-check that
video_fileis used in both RestSharp'sAddFileand PHP's$_FILES['video_file']. A typo here is the #1 cause of failed uploads. - Server Firewall/Proxy: Ensure your WPF app can reach the server — test the API endpoint with Postman first to rule out network issues.
- RestSharp Version: Make sure you're using the latest stable version of RestSharp (install via NuGet). Older versions had bugs with multipart file uploads.
- Large Files: For videos over 100MB, consider adding chunked upload logic, but start with smaller test files first to confirm basic functionality.
4. Debugging Tips
- Check Server Responses: In your WPF code, always print
response.Contenteven whenIsSuccessfulis false — the PHP error messages will point you directly to the problem. - Log PHP Requests: Add this line at the top of your PHP script to log incoming requests (helps confirm if the file is reaching the server):
file_put_contents('upload_log.txt', print_r($_FILES, true) . "\n" . print_r($_POST, true) . "\n\n", FILE_APPEND);
内容的提问来源于stack exchange,提问作者Viakode
相关产品推荐
相关产品推荐

