Realicé la carga de archivos usando formdata y axios en laravel. Pero hubo un problema con la recuperación del archivo

Código de script:

let formData = new FormData();
formData.append('myfile', self.files);

axios({
    method: 'POST',
    url: '/api/save',
    data: formData,
    headers: {
        'Content-Type': 'multipart/form-data'
    },
}).then(function (res) {
    console.log(res.data);
});

Y recupero en MyController:

public function save(Request $request) {
    $response = array();
    $response['a'] = $request->file('myfile')
    $response['b'] = $request->myfile;
    return Response::json($response);
}

Luego, verifique la consola:

{a: null, b: "[object File]"}
    a: null
    b: "[object File]"
    __proto__: Object

No sé por qué usa propiedades dinámicas y no usa el método de archivo .

1
Chang Seob. Kim 10 sep. 2018 a las 05:52

3 respuestas

La mejor respuesta

Subo archivos en Laravel usando Vue de esta manera.

Ruta (api.php)

Route::post('/upload','mainController@upload');

Controlador

public function upload(Request $request){
  $user = User::create($request->only('name'));
   if($request->image) {
        $filename ='_logo_' . str_random(40); 
        //make  directories in public folder as public->uploads->users
        $imagePath = '/uploads/users/' . $filename;
        //use intervention/image package to handle images
        Image::make($request->image)->save(public_path($imagePath));
        $user->image = $filename;
        $user->save();
    }

    return response()->json(['status' => 'success','message' => 'Image was uploaded successfully'],200);
}

Vue.js plantilla

<template>
    <div class="container">
       <form class="needs-validation" novalidate @submit.prevent="uploadImage()">
         <div class="col-md-6 mb-3">
              <input type="file" @change="onFileChange" />
              <div class="card" style="width: 18rem;">
                   <img class="card-img-top" :src="logo" alt="Card image cap">
              </div>
         </div>
         <button class="btn btn-primary btn-lg btn-block" type="submit">Upload</button>
       </form>
      </div>
</template>

secuencia de comandos

export default{
    data(){ 
      return{ 
              logo : null,
              requesting_upload_file:false,

             } 

    },
    methods:{
         onFileChange(e) {
            let files = e.target.files || e.dataTransfer.files;
            if (!files.length)
                return;
            this.createImage(files[0]);
        },
        createImage(file) {
            let reader = new FileReader();
            let vm = this;
            reader.onload = (e) => {
                vm.logo= e.target.result;
            };
            reader.readAsDataURL(file);
        },
        uploadImage(){
            let formData = new FormData();
            const config = {
                headers:{'Content-Type' : 'multipart/form-data'}
            };

            if(this.logo){formData.append('logo', this.logo);}

            this.requesting_upload_file = true;
            axios.post('/api/upload',formData,config).then(response => {
               this.requesting_upload_file = false;
               console.log(response)
            }).catch(error => {
                this.requesting_upload_file = false;
                alert(error)
            })
        },
    }
}
1
Afraz Ahmad 5 mar. 2020 a las 18:52

Prueba esto

uploadPhoto: function(){
            let that = this;
            let formData = new FormData();
            formData.append('file', that.photo.file);                 
            axios.post( '/api//save_photo',
            formData,
                {
                headers: {
                'Content-Type': 'multipart/form-data'
                }
                }
                ).then(function(response){
                    that.errors = response.data.success;
                })
                .catch(function(){
                console.log('FAILURE!!');
                });
            }
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;
use Image;
use File;

protected function saveFilms(Films $request)
    {

        $dir_path = 'uploads/images';
        $dir_path_resize = 'uploads/images/45x45';
        if( $request ){
            $filmsObj = new Film();
            if (!File::exists($dir_path))
            {
                File::makeDirectory($dir_path, 0775, true);
            }
            if (!File::exists($dir_path_resize))
            {
                File::makeDirectory($dir_path_resize, 0775, true);
            }
            if ( $request->file ) {
                $file  = $request->file;
                $extension = $file->getClientOriginalExtension(); 
                $file_name = 'films_'.\Carbon\Carbon::now().'.'.$extension; 
                $file->move($dir_path, $file_name); 
                $image = Image::make(public_path($dir_path.'/'.$file_name));
                $image->resize(null, 45, function ($constraint) {
                $constraint->aspectRatio();
            });
                $image->save(public_path($dir_path_resize.'/'.$file_name));
        }
            return $return_array;
    }
}

Pruebe el código anterior, la esperanza funcionará.

0
leaveme_alone 19 ene. 2019 a las 04:59

Intente agregar lo siguiente a sus encabezados:

        'contentType': false,
        'processData': false
0
Aierto 10 sep. 2018 a las 03:11