猿问

使用vue axios和PHP上传多个文件 - 只上传一个文件

我正在尝试使用 vue 和 axios 创建多个文件上传。我的问题是只有ine 文件会上传到服务器。这是我使用的代码:模板代码


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

JS代码


//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服务器代码


// 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();


如何上传多个文件?也许我需要修改代码?


慕姐8265434
浏览 131回答 1
1回答

慕田峪4524236

append尝试将函数中的“image”更改为“image[]”例子:for(let i;i < $refs.images.files.length; i++){&nbsp;let file = this.$refs.images.files[i];&nbsp;formData.append('image[]', file);}在服务器中$uploadedFiles=$request->getUploadedFiles();foreach ($uploadedFiles['image'] as $uploadedFile) {&nbsp; &nbsp; &nbsp; &nbsp; if ($uploadedFile->getError() === UPLOAD_ERR_OK) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答