如何在nuxt js和laravel 7中上传图像 [英] How upload an image in nuxt js and laravel 7

查看:41
本文介绍了如何在nuxt js和laravel 7中上传图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在nuxtjs前端和laravel后端开​​发了一个电子商务应用程序,但是很难上传图像并将其保存在数据库中,有人可以帮我解决这个问题吗?

I develop an ecommerce application in nuxtjs frontend and laravel backend.But it is difficult to upload image and save it in the database.Can anyone help me solve the problem ?

推荐答案

以下是使用Laravel API的Nuxt或Vuejs图像上传器的示例.我在代码中给您留下了评论.

Here example of Nuxt Or Vuejs image uploader with Laravel API. I left a comment inside the code for you.

首先,您必须使用此内容制作upload.vue组件.

First of all, you must make upload.vue component with this content.

<template>
  <div class="container">
    <label class="custom-file" for="file">
      {{files.length ? `(${files.length}) files are selected` : "Choose files"}}
      <input @change="handleSelectedFiles" id="file" multiple name="file" ref="fileInput" type="file">
    </label>

    <!--Show Selected Files-->
    <div class="large-12 medium-12 small-12 cell">
      <div class="file-listing" v-for="(file, key) in files">{{ file.name }} <span class="remove-file" v-on:click="removeFile( key )">Remove</span></div>
    </div>

    <!--Submit Button && Progress Bar-->
    <div>
      <button @click="upload">Start Upload</button>
      - Upload progress : {{this.progress}}
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        files   : [],
        progress: 0
      }
    },
    computed: {
      /*The FormData : Here We Make A Form With Images Data To Submit.*/
      form() {
        let form = new FormData();

        this.files.forEach((file, index) => {
          form.append('files[' + index + ']', file);
        });

        return form;
      }
    },
    methods : {
      handleSelectedFiles() {
        let selectedFiles = this.$refs.fileInput.files;

        for (let i = 0; i < selectedFiles.length; i++) {
          /*Check Already Has Been Selected Or Not ...*/
          let isFileExists = this.files.find(file => file.type === selectedFiles[i].type && file.name === selectedFiles[i].name && file.size === selectedFiles[i].size && file.lastModified === selectedFiles[i].lastModified);

          if (!isFileExists)
            this.files.push(selectedFiles[i]);
        }
      },
      removeFile(key) {
        this.files.splice(key, 1);
      },
      upload() {
        const config = {
          onUploadProgress: (progressEvent) => this.progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        };

        this.$axios.post('host-url/upload-image', this.form, config)
          .then(res => {
            this.progress = 0;
            this.files = [];

            console.log(res)
          })
          .catch(err => console.log(err))
      }
    }
  }
</script>

<style>
  .custom-file {
    padding: 1.2rem;
    border-radius: .8rem;
    display: inline-block;
    border: 2px dashed #a0a0a0;
  }

  .custom-file input {
    display: none;
  }
</style>

此后,我们必须在Laravel API路由中创建一个端点,如下所示:

After this, we must make an endpoint in Laravel API routes like this:

Route::post('/upload-image', 'UploadController@image');

最后,将这段代码上传

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UploadController extends Controller
{
    public function image(Request $request)
    {
        $request->validate([
            'files'   => ['required', 'array'],
            'files.*' => ['required', 'image','min:5','max:5000']
        ]);

        $uploadedFiles = [];

        foreach ($request->file('files') as $file) {
            $fileName = bcrypt(microtime()) . "." . $file->getClientOriginalExtension();
            $file->move('/uploads', $fileName);
            array_push($uploadedFiles, "/uploads/{$fileName}");
        }

        return response($uploadedFiles);
    }
}

注意:localhost中的进度非常快,因此如果要在本地对其进行测试,请上传大于50 MB的文件.

Attention: Progress in localhost is so fast, then if you want to test it in local upload a file largest than 50 MB.

这篇关于如何在nuxt js和laravel 7中上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆