victordelaunay's avatar

How to upload multiple images with Dropzone

Hi! I want to use Dropzone to upload multiple images to my S3 storage. But here's where I get stuck. I've basically got an admin panel where I can create a product through a form in which I can upload a thumbnail to it. The problem with Dropzone is that it immediately uploads the files to an endpoint. I want Dropzone to only upload when the whole form is submitted, so that I can retrieve the product name from the form, create a folder with that name and store the file inside that very folder. Maybe I'm doing things in the wrong order :/ Thanks in advance.

0 likes
3 replies
burlresearch's avatar

I wouldn't try to fight Dropzone. I would:

  • let it upload the files to your Laravel server as soon as they are dropped
  • verify the upload is roughly what you expect
  • store the files locally
  • return the pathname
  • store those pathnames as a hidden input in the form
  • then, when the form is completed and validated, grab those files and upload them to S3

Here is an upload() function that I have used:

public function upload(Request $request)
{
    \Log::debug(__METHOD__, $request->toArray());
    $response = ['status' => 'ack'];

    if ($request->hasFile('file') && ($request->file->isValid())) {
        $fname = sprintf("%s-%s", date('ymdhis'), $request->file->getClientOriginalName());

        $stored             = $request->file->storeAs('uploads', $fname);
        $response['stored'] = $stored;

        if ($this->checkValidUploadType($stored)) {
            ImportJob::dispatch($stored);   // artisan make:job ImportJob
        } else {
            unlink(storage_path('app/' . $stored));
            abort(406, 'Unrecognized CSV header.');
        }
    } else {
        $response['status'] = 'error: during upload';
    }

    return $response;
}
Snapey's avatar

The alternative approach I would try is;

a) create a random string and send it to the view to be used in a hidden field

b) that hidden field will be passed back with each file upload

c) store the images in a folder, using the random string

d) when the form is submitted, rename the folder with the random token to the name you have given (or id)

Please or to participate in this conversation.