【问题标题】:using nuxtjs and filepond to send images to a laravel API使用 nuxtjs 和 filepond 将图像发送到 laravel API
【发布时间】:2021-09-13 12:23:56
【问题描述】:

我有一个使用 vue-filepond 适配器的 nuxt 前端,用户可以选择使用该帖子上传图片。然后将其发送到处理请求的 laravel API。

<client-only>
  <file-pond
    name="image"
    ref="pond"
    class="filepond"
    :allow-multiple="false"
    accepted-file-types="image/jpeg, image/png"
    server="http://127.0.0.1:8000/api/posts"
    allowRevert="false"
    :files="form.image"
  />
</client-only>

主要使用默认的文件池选项,

data() {
  return {
    errors: [],

    form: {
      title: '',
      content: '',
      image: [],
    }
  }
},

数据像这样上传到api

methods: {
  createPost() {
    this.$axios.$post('http://127.0.0.1:8000/api/posts', this.form)

    this.$toast.show({
      type: 'success',
      title: 'Success',
      message: 'Your post has been created'
    })
  }
}

现在由于 filePond 是异步的,所以文件在我发布时比我的表单更早上传。

所以在 laravel 部分

public function store(Request $request): void
{
    if ($request->hasFile('image')) {
        $path = Storage::putFile('avatars', $request->file('image'));
    }

    $request->validate([
        'title' => 'required|string|max:24',
        'content' => 'required|string|max:254',
        'image' => 'nullable|image'
    ]);

    Post::create([
        'title' => $request->get('title'),
        'slug' => Str::slug($request->get('title'), '-'),
        'content' => $request->get('content'),
        'image' => $path ?? null
    ]);
}

图像将被存储,但如果我在表单上单击提交以上传标题和某些内容,则 Post::create 方法中的 ìmage 部分始终为 NULL。

我怎样才能使 filePond 不再异步上传?这样当我在我的表单上点击提交时,标题、内容和图像都会被平等地上传

【问题讨论】:

  • 前端实际上是在构建查询并在一切设置好后发送它。它不应该在之后发送一些数据和其他一些数据。前端的async 部分本质上是在说“我正在等待后端回答而不阻塞线程”,因为它可能需要 200 毫秒到 5 秒。
  • 嗯,那filePond是怎么上传的呢?当我选择一张图片时,它会开始上传,直到达到 100%。然后当我想上传我的“主要”表单时,例如标题和内容,图片不是用帖子创建的。
  • 看看事件和方法:pqina.nl/filepond/docs/api/instance/events 如果我理解正确,你想同时发送图像和一些表单输入?注意图像的上传完成事件,并且在被表单下方的submit 按钮以编程方式触发之前不要发布到 API。
  • 是的,上传一张图片(通过文件池)和一些通过表单的文本和内容就是我正在寻找的全部
  • 尝试查找我之前评论中所说的可用事件和方法。

标签: laravel nuxt.js


【解决方案1】:

感谢 Kissu 并阅读了 filePond 的文档。

const file = this.$refs.pond.getFiles()[0].file

const data = new FormData()

data.append('title', this.form.title)
data.append('content', this.form.content)
data.append('image', file)

this.$axios.$post('http://127.0.0.1:8000/api/posts', data)

在你的后端(在我的例子中是 laravel)

if ($request->hasFile('image') && $request->file('image')->isValid()) {
  $post->addMediaFromRequest('image')->toMediaCollection('image');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-17
    • 2016-09-10
    • 2017-02-28
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2016-05-06
    • 2014-04-09
    相关资源
    最近更新 更多