1

I'm trying to create a multiple file upload using vue and axios. My problem is that Only ine file will be uploaded to the server. Here is the code I' using: Template code

<input type="file" name="images[]" multiple ref="images" @change="handleUpload()">

JS code

//this is part of the handleUpload() vue method.

let formData = new FormData();

for(let i;i < $refs.images.files.length; i++){
 let file = this.$refs.images.files[i];
 formData.append('image', file);
}

axios.post('/upload', formData, { header: { 'Content-Type': 'multipart/form-data' } })
.then( (response) => console.log(response, response.data) )
.catch( (error) => console.log(error) ); 

PHP server code

// I'm using slim 4 and sirius upload to manage the file validation/upload
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\UploadedFileInterface;
use Slim\Factory\AppFactory;
use Sirius\Upload\Handler as UploadHandler;

require __DIR__ . '/vendor/autoload.php';

$app = AppFactory::create();

$app->post('/platform/api/v1/compress', function(Request $request, Response $response){

    $uploadHandler = new UploadHandler('/uploads');
    
        $uploadHandler->addRule('extension', ['allowed' => ['jpg', 'jpeg', 'png']]);
   
        $result = $uploadHandler->process( $request->getUploadedFiles() );
        
        // handle single input with single file upload
        if( $result->isValid() ){
            $result->confirm();
                   
            $url = ["master_image_url" => "/uploads/".$result->name];

            $response->getBody()->write(json_encode($url));
        }


    return $response;
});

$app->run();

How I can upload multiple files?Maybe I need to modify the code?

1 Answer 1

2

try changing "image" for "image[]" in the append function

Example:

for(let i;i < $refs.images.files.length; i++){
 let file = this.$refs.images.files[i];
 formData.append('image[]', file);
}

in server

$uploadedFiles=$request->getUploadedFiles();
foreach ($uploadedFiles['image'] as $uploadedFile) {
        if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
           
        }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

I need to test but I think that the problem is also with the server side code?not sure about
I think you should add foreach $request->getUploadedFiles()
I'm not sure about this, slim will provide a UploadedFileInterface object that will contain uploaded files. The Sirius library that I'm using to manage the upload process will accept and handle the PSR-7 UploadedFileInterface object, maybe there is some function that will handle multiple files but I'm not sure

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.