gauravhiran85's avatar

The GET method is not supported for route api/add_edit_media. Supported methods: POST

I am trying to upload an image of 800 MB to the api add_edit_media. On POSTMAN this API works as expected. But when api is called using axios it is returing the 405 error.

What all configuration needs to be checked from server point of view?

0 likes
22 replies
Snapey's avatar

please format your question

does the request reach this controller?

how are you sending the request?

gauravhiran85's avatar

Yes it is reaching the controller @snapey Via POSTMAN it is working fine. But while calling this API via axios API is returing 405 error

Snapey's avatar

@gauravhiran85 if its reaching the controller then the error with get route must occur after your method or on validation

gauravhiran85's avatar

@snapey Everything is working fine when the file size is less than 10MB, but while uploading large files greater than 10MB, the api is throwing error.

gauravhiran85's avatar

@Snapey php.ini settings max_execution_time = 28800 max_input_time = 800 max_input_vars = 100 memory_limit = -1 post_max_size = 1000000M upload_max_filesize = 1000000M

tykus's avatar

Perhaps if you shared your code (client-side and server-side)???

gauravhiran85's avatar

@tykus Server-side code

public function addEditMedia(Request $request){
        try{
            ini_set('max_execution_time', 3600);
            $user_id = auth()->user()->id;
            $validator = Validator::make($request->all(),[
                                                'design_id' => 'required',
                                                'image' => 'sometimes|required|image|mimes:jpg,jpeg,png|max:80000', 
                                                'document' => 'sometimes|required|file|mimetypes:application/pdf,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/msword,image/vnd.adobe.photoshop|max:80000', 
                                                'license_document' => 'sometimes|required|file|mimetypes:application/pdf,jpeg,jpg,png|max:80000', 
                                                'open_files' => 'sometimes|required|mimetypes:image/vnd.adobe.photoshop|max:80000',
                                                'font_files' => 'sometimes|required|mimetypes:font/opentype,font/ttf,font/sfnt|max:10000',
                                            ]
                            );
            
            if($validator->fails()){    
                return $this->commonHelper->apiValidatorErrorStructure(RESPONSE::HTTP_BAD_REQUEST, $validator->errors()->messages());
            }

            $dir = "";
            $type = 0;
            $design_id = base64_decode($request->design_id);

            DB::beginTransaction();

                $design_image = new DesignMedia();
                $design_image->design_id = $design_id;

                if($request->has("image")){
                    $type = 1;               
                    $image = $request->image;
                }elseif($request->has("document")){
                    $type = 2;
                    $image = $request->document;
                }elseif($request->has("license_document")){
                    $type = 3;
                    $image = $request->license_document;
                }elseif($request->has("open_files")){
                    $type = 4;
                    $image = $request->open_files;
                }elseif($request->has("font_files")){
                    $type = 5;
                    $image = $request->font_files;
                }else{
                    DB::rollBack();
                    return $this->commonHelper->apiErrorStructure(RESPONSE::HTTP_BAD_REQUEST,'Media is required.');    
                }

                $image_name = Carbon::now()->timestamp.'_'.str_replace(" ","_",trim($image->getClientOriginalName()));
                
                 //Save the images in temp folder
                $dir = "temp_folder";

                //Also move the image to the Storage folder/s3 bucket
                if (!@is_dir(storage_path($dir))) {
                    @mkdir(storage_path('app/public').DIRECTORY_SEPARATOR.$dir, 0777, true);
                }

                
                //$image->move(storage_path().DIRECTORY_SEPARATOR.$dir,$image_name);
                Storage::disk('public')->put($dir.DIRECTORY_SEPARATOR.$image_name, $image);
                

                $design_image->design_media_type = $type;
                $design_image->design_media_name = $image_name;
                $design_image->save();

                $media_id = base64_encode($design_image->id);
                
               

            DB::commit();

            return $this->commonHelper->apiResponseStructure(RESPONSE::HTTP_OK,'Success',['media_id' => $media_id]);
        }catch(Exception $e){
            DB::rollback();
            $error_subject = "Add Edit Media";
            $this->commonHelper->generateErrorLog($user_id,$error_subject,$e);
            return $this->commonHelper->apiErrorStructure(500,'Something Went Wrong!');
        }
    }
tykus's avatar

@gauravhiran85 please format your code correctly by wrapping it within triple backticks

```
// your code
```

Also, you need to provide the axios request code since that seems to be the problem.

1 like
gauravhiran85's avatar

@tykus Axios Code

const imageUploads = async () => {
    try {
      for (
        let index = currentImageIndex;
        index < selectedImageForUpload.length;
        index++
      ) {
        const formData = new FormData();
        formData.append(`image`, selectedImage[imageIndex]);
        formData.append(`design_id`, designId);
        const response = await api.post(url.addEditMedia, formData, {
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total
            );
            setSelectedImageForUpload((prevFiles) => {
              const newFiles = [...prevFiles];

              if (index >= 0 && index < newFiles.length) {
                newFiles[index].percentage = percentCompleted;
              } else {
                newFiles.forEach(
                  (file) => (file.percentage = percentCompleted)
                );
              }
              return newFiles;
            });
          },
          cancelToken: new CancelToken(
            (cancel) => (cancelImageUpload.current = cancel)
          ),
        });

        console.log(`API call for file ${index + 1} completed:`, response);
      }
      setCurrentImageIndex((prevIndex) => prevIndex + selectedImage.length);
      setImageIndex((prevIndex) => prevIndex + 1);
      setIsImageUploading(false);
      setSelectedImageError("");
    } catch (error) {
      console.error("Image uploads failed:", error);
      if (isCancel(error)) {
        console.log(error.message);
      }
      setIsImageUploading(false);
    }
  };
tykus's avatar

@gauravhiran85 is the url.addEditMedia value giving the correct URL?

Is the ContentType header being set to multipart/form-data somewhere in the Request?

tykus's avatar

@gauravhiran85 and it is making a POST or GET request (in Devtools)??? Are you seeing all of the requests being made whenever you submit the form?

tykus's avatar

@gauravhiran85 if you have registered this route...

Route::post('api/add_edit_media', [YourController::class, 'addEditMedia']);

...and you are making a POST Request to that URL; then it should be working.

What was different about the Postman request; URL, headers, payload etc?

Snapey's avatar

my first check would be to look in the dev tools, see the form request, check the url, check the verb, check the payload, check csrf present and accurate, then check the response.

gauravhiran85's avatar

It was php ini issue my local values and master values were different. Discussion will be closed.

Please or to participate in this conversation.