You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel部署服务器后S3图片上传报hashName()空指针错误求助

Fixing "Call to a member function hashName() on null" When Uploading Base64 Images to S3 in Laravel

Let's break down why this error is happening and how to fix it. First, the error occurs because somewhere in the flow, Laravel's FilesystemAdapter is trying to call hashName() on a null value—this happens almost exclusively when an UploadedFile instance is expected but null is passed instead.

Why This Happens (Local vs Server)

Your local setup works because you're sending valid base64 image strings, but on the server, the prescription field is either:

  1. A null value that somehow bypassed validation
  2. An actual file (UploadedFile instance) instead of a base64 string (if your frontend changed how it sends data in production)
  3. A corrupted/invalid base64 string that fails processing

Step-by-Step Fixes

1. Strengthen Validation to Ensure Valid Base64 Input

First, update your validation rules to enforce that prescription is a valid base64 string. This will block invalid inputs before they reach your upload logic:

$validator = Validator::make($request->all(), [
    'patient_id' => 'required',
    'appointment_id' => 'required',
    'prescription' => 'required|string|base64' // Add string + base64 checks
]);

2. Rewrite the Upload Helper for Robustness

Your current uploadImage method has fragile string parsing and lacks type checks. Let's make it more resilient:

<?php
namespace App\Helpers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;

class UserHelper {
    public static function uploadImage($image) {
        try {
            // Reject non-string inputs immediately
            if (!is_string($image)) {
                throw new \Exception('Image data must be a base64 string');
            }

            // Validate base64 image format
            $base64Pattern = '/^data:image\/(\w+);base64,/';
            if (!preg_match($base64Pattern, $image, $matches)) {
                throw new \Exception('Invalid base64 image format');
            }

            $extension = $matches[1];
            $fileName = now()->timestamp . '_' . uniqid() . '.' . $extension;

            // Decode base64 (with strict mode to catch invalid data)
            $imageData = base64_decode(preg_replace($base64Pattern, '', $image), true);
            if ($imageData === false) {
                throw new \Exception('Failed to decode base64 image data');
            }

            // Upload to S3 and verify success
            $uploadSuccess = Storage::disk('s3')->put($fileName, $imageData, 'public');
            if (!$uploadSuccess) {
                throw new \Exception('Failed to upload image to S3');
            }

            return $fileName;
        } catch (\Exception $e) {
            // Log the error for debugging (critical for server issues)
            Log::error('Image upload failed: ' . $e->getMessage());
            return false;
        }
    }
}

3. Handle Upload Failures in the Controller

Don't proceed with database operations if the upload fails. Update your controller to check the upload result:

public function uploadPrescription(Request $request){
    $validator = Validator::make($request->all(), [
        'patient_id' => 'required',
        'appointment_id' => 'required',
        'prescription' => 'required|string|base64'
    ]);
    if($validator->fails()){
        return $this->sendError('Validation Error.', $validator->errors());
    }

    $input = $request->all();
    $status_check = Appointment::where('id','=',$input['appointment_id'])->first();
    
    if($status_check->status == 'OnGoing'){
        $imageName = UserHelper::uploadImage($request->prescription);
        
        // Abort if upload fails
        if (!$imageName) {
            return response()->json([
                'message' => "Prescription Uploading Failed", 
                'error'=> 1, 
                'status'=> 0 
            ]);
        }

        $data = [
            'patient_id' => $input['patient_id'],
            'appointment_id' => $input['appointment_id'],
            'prescription' => $imageName
        ];
        
        $profile = Prescriptions::updateOrCreate($data);
        return response()->json([
            'message' => "Prescription Uploaded", 
            'profile'=>$profile, 
            'error'=> 0, 
            'status'=> 1 
        ]);
    }else{
        return response()->json([
            'message' => "Prescription Uploading Failed", 
            'error'=> 1, 
            'status'=> 0 
        ]);
    }
}

4. Verify Server Environment Configuration

  • Check S3 Credentials: Ensure your server's .env file has valid AWS credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION, AWS_BUCKET) and that the server has network access to S3.
  • PHP Limits: Increase post_max_size and upload_max_filesize in your server's php.ini to accommodate large base64 strings (base64 data is ~30% larger than the original file).

内容的提问来源于stack exchange,提问作者Ryuk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 13:02:57