首页 > 解决方案 > 我无法使用 Vue 2.6 和 Laravel 8.5(Docker 应用程序)上传图像

问题描述

我需要将图像上传到公共文件夹。正常的事情,我已经解决了一个类似的问题,我没有遇到任何问题。但是现在,我不明白,哪里有问题。

我的Vue数据: Vue数据图片预览

我的 Axios 功能:

this.productImages.forEach( image => {

    let data = new FormData()
    data.set('image', image.file)

    console.log(image.file)

    axios.post('/api/image', data, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }})
        .then( response => {
            console.log( response.data.status )
            this.uploading.status = "Images uploading."
        })
        .catch( errors => {
            console.log("uploading error")
        })
    });
}

image.file 的控制台日志如下所示: image.file 图像预览的控制台日志 我认为,在这个控制台日志文件中看起来不错,或者?

当我尝试检查来自 Laravel 的请求时: Laravel store funcion without image save preview

我得到空对象: 请求控制台日志图像预览

当我尝试将图像保存到公用文件夹时,如下所示:

$image->move( public_path('images/uploads'), "testName" );

我收到一条错误消息:

POST http://localhost/api/image 500 (Internal Server Error)

拜托,有人有一些想法,哪里有问题?

标签: file-uploadvuejs2laravel-8

解决方案


  1. 尝试不设置任何标题,根据我的经验,当axios接收到一个FormData对象时,它会自动应用正确的标题,并且 Laravel 很高兴地接受了上传。

  2. 尝试append而不是set因为一些奇怪的原因不久前,我记得.set()没有工作,但.append()即使我将一个键值对设置在FormData.

至于存储,请确保您已运行php artisan storage:link https://laravel.com/docs/8.x/filesystem#the-public-disk

config/filesystems.php您可以在其中配置自定义磁盘空间'disks' => [ ... ]

您可以向该数组添加这样的配置:


        'uploads' => [
            'driver' => 'local',
            'root' => storage_path('public/uploads'),
            'url' => env('APP_URL') . '/storage/uploads',
            'visibility' => 'public'
        ],

uploads然后使用名为: https ://laravel.com/docs/8.x/filesystem#automatic-streaming的自定义磁盘


$file = $request->file('image');

Storage::disk('uploads')->putFileAs(DIRECTORY_SEPARATOR, $file, $file->getClientOriginalName());


推荐阅读