1

I am creating a media API for the first time creating an API.

I have this code:

/**
* Store a newly created resource in storage.
*
* @param  \App\Http\Requests\UploadRequest $request
* @return \Illuminate\Http\Response
*/
public function store(UploadRequest $request)
{
    if(!$request->hasFile('fileName')) {
        return response()->json(['upload_file_not_found'], 400);
    }
    $file = $request->file('fileName');
    if(!$file->isValid()) {
        return response()->json(['invalid_file_upload'], 400);
    } 

    if($request->hasfile('fileName'))
    {
        $media = new Media();
        $data = array();
        foreach($request->file('fileName') as $image)
        {
            $rdm = uniqid(5);
            $name= $rdm .'-'.$image->getClientOriginalName();
            $image->move(public_path().'/images/', $name);
            $data[] = $name;

        }

        $media->fileName = json_encode($data);
        $media->clientId = $request->clientId;
        $media->uploadedBy = Auth::user()->id;
        $media->save();

    }

    return ["success" => "Your media file has been successfully uploaded"];
}

Please can you help me why it doesn't upload the images into the public path. It also doesn't store anything in the database. I get a 200 code from postman when sending my POST request, however the database has an empty array as the fileName?

**** EDIT ****

I am uploading multiple images. There isnt a form for this as i am making an api for a mobile app. The request is a POST request to URL /api/v1/media

7
  • are you uploading multiple images? Commented Dec 10, 2018 at 10:08
  • @LuckySaini I am yes, i have updated my post now :) Commented Dec 10, 2018 at 10:10
  • Can you add the HTML of your form? Commented Dec 10, 2018 at 10:12
  • 1
    @StevenHardy check public/images directory permission. This should be writable directory. Commented Dec 10, 2018 at 10:13
  • 1
    What is your request type? I mean it should be formData Commented Dec 10, 2018 at 10:16

3 Answers 3

2

Here is the solution i come up with that works :)

This uploads multiple files and checks the extension for valid files.

public function store(UploadRequest $request)
{
    if(!$request->hasFile('fileName')) {
        return response()->json(['upload_file_not_found'], 400);
    }

    $allowedfileExtension=['pdf','jpg','png'];
    $files = $request->file('fileName'); 
    $errors = [];

    foreach ($files as $file) {      

        $extension = $file->getClientOriginalExtension();

        $check = in_array($extension,$allowedfileExtension);

        if($check) {
            foreach($request->fileName as $mediaFiles) {
                $media = new Media();
                $media_ext = $mediaFiles->getClientOriginalName();
                $media_no_ext = pathinfo($media_ext, PATHINFO_FILENAME);
                $mFiles = $media_no_ext . '-' . uniqid() . '.' . $extension;
                $mediaFiles->move(public_path().'/images/', $mFiles);
                $media->fileName = $mFiles;
                $media->clientId = $request->clientId;
                $media->uploadedBy = Auth::user()->id;
                $media->save();
            }
        } else {
            return response()->json(['invalid_file_format'], 422);
        }

        return response()->json(['file_uploaded'], 200);

    }
}
Sign up to request clarification or add additional context in comments.

Comments

0
public function store(Request $request)
{

    if ($this->getErrorIfAny($request->all(), $this->ruls)) {
        return $this->getErrorIfAny($request->all(), $this->ruls);
    }

    if (!$request->hasFile('image_url')) {
        return response($this->getResponseFail(trans('my_keywords.uploadFileNotFound'), false), 400);
    }

    $allowedfileExtension = ['jpg', 'png', 'jpeg'];

    $files = $request->file('image_url');

    $number_photos_upload = count($files);

    $pictures_available_upload = array();

    for ($i = 0; $i < count($files); $i++) {
        $extension = $files[$i]->getClientOriginalExtension();

        $check = in_array($extension, $allowedfileExtension);

        if ($check) {
            $pictures_available_upload[$i] = $files[$i];
        }
    }

    $number_images_success_uploded = 0;

    $images_urls = array();

    for ($i = 0; $i < count($pictures_available_upload); $i++) {

        $image = $pictures_available_upload[$i];

        $path = config('paths.storage_path') .
            $image->store(config('paths.store_image_path'), 'public');

        //store image file into directory and db
        $store_images = new StoreImages();
        $store_images['store_id'] = $request['store_id'];
        $store_images['image_url'] = $path;
        $result = $store_images->save();
        if ($result) {
            $images_urls[$i] = $path;
            $number_images_success_uploded = $number_images_success_uploded + 1;
        }
    }

    if ($number_images_success_uploded == 0) {
        return response($this->getResponseFail(trans('my_keywords.invalidFileFormat'), false), 422);
    } else {
        $data = [
            'store_id' => (int) $request['store_id'],
            'number_photos_upload' => $number_photos_upload,
            'number_images_success_uploded' => $number_images_success_uploded,
            'images' => $images_urls,
        ];
        return response($this->getResponse(__('my_keywords.operationSuccessfully'), true, $data), 200);
    }
}

1 Comment

Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made.
-1

send as binary for api .

php file_get_contents

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.