Laravel视频文件上传异常求助:文件保存为tmp而非MP4格式
Hey there, let’s tackle this frustrating issue where your Laravel video uploads are ending up as those random phpXXXX.tmp files instead of proper MP4s. I’ve run into similar headaches before, so let’s break down the most likely fixes:
Double-check how you’re naming the uploaded file
The #1 culprit here is usually not grabbing the original file’s extension when saving. Laravel’sUploadedFileobject gives you access to the original filename and extension—make sure you’re using those instead of the temporary filename.Here’s a common mistake to avoid:
// ❌ Wrong: Uses the temporary filename directly $request->file('video')->storeAs('videos', $request->file('video')->getFilename());And here’s the correct approach, which preserves the MP4 extension (plus adds a timestamp to avoid filename collisions):
// ✅ Correct: Builds a proper filename with original extension $videoFile = $request->file('video'); $baseName = pathinfo($videoFile->getClientOriginalName(), PATHINFO_FILENAME); $extension = $videoFile->getClientOriginalExtension(); $newFileName = $baseName . '_' . time() . '.' . $extension; // Save to your desired disk (e.g., 'public') $videoFile->storeAs('videos', $newFileName, 'public');Verify your upload validation rules
If you’re not validating the file type correctly, you might be allowing unexpected files through, or even causing silent failures that lead to tmp files sticking around. Make sure your validation includes MP4 (and any other video types you need):$request->validate([ 'video' => 'required|file|mimes:mp4,mov,avi|max:10240', // Adjust max size as needed ]);The
mimes:mp4rule ensures only MP4 files are accepted, which helps prevent invalid files from being processed incorrectly.Check storage directory permissions
Sometimes, if the web server user (likewww-dataon Apache) doesn’t have write permissions to your storage directory, Laravel might fail to rename the temporary file properly. Run these commands to fix permissions (adjust paths if needed):chown -R www-data:www-data storage/ chmod -R 755 storage/Avoid misusing third-party upload packages
If you’re using a package to handle uploads (like for processing, though that’s less common for videos), double-check that it’s configured to preserve the original file extension. Some packages might default to using temporary filenames if you don’t explicitly set the output format.
Start with checking your filename generation logic—this is almost always the root cause. If that doesn’t fix it, move on to validation and permissions.
内容的提问来源于stack exchange,提问作者user7907489

