Laravel将图像从Vue发送到控制器

时间:2019-12-16 15:07:33

标签: laravel

我正在尝试在更新项目时保存图像,但是在将文件发送到控制器以进行保存时遇到问题。这就是我的发送方式

submit(item) {
    this.$refs.ruleForm.validate((valid) => {
        if (valid) {
            this.loading = true;
            this.$inertia.post('/courses/' + item.id, {
                name: this.ruleForm.name,
                summary: this.ruleForm.summary,
                description: this.ruleForm.description,
                price: this.ruleForm.price,
                hours: this.ruleForm.hours,
                min_grade: this.ruleForm.min_grade,
                file: this.imagen,
                matery: this.matery,
                remover: this.remover,
                strict: this.strict
            }).then(
                () => {
                    this.$message({
                        type: 'success',
                        message: 'Guardado correctamente.'
                    });
                    this.loading = false
                },
                (res) => {
                    this.$message.error(parseError(res)[0]);
                    this.loading = false;
                })
        } else {
            return false;
        }
    });
},

如果我在{{imagen}}和{{imageUrl}}中分别是结果,这就是为什么我发送imagen而不是url的原因

[object File] 

blob:http://dev.inae.com/9c77fa72-b778-45c9-8ab2-0a9084282415

当我Log::info($request)时,这是输出,在添加文件,更改文本并保存时,

local.INFO: array (
  'name' => 'Principiante Clase 3 (automático)',
  'summary' => 'Enseñaremos a compresionar el vehículo y la utilización de 
                cambios en vehículo automático',
  'description' => '<p>Enseñaremos a compresionar el vehículo y la utilización de 
                cambios en vehículo automático (viaje a fraijanes).</p>',
  'price' => 52000,
  'hours' => 2,
  'min_grade' => 70,
  'file' => 
  array (
    'uid' => 1576507762527,
  ),
  'matery' => NULL,
  'remover' => false,
  'strict' => false,
)  

但是,如果我仅添加图像而不进行任何其他更改,则日志中什么也不会发生

在更新功能中用于更新控制器中图像的代码

//Log is here
$editCourse = Course::find($id);
$destino = "img/courses";
$link = public_path();

if ($request->hasFile('file')) {
    if (!empty($editCourse->image) && file_exists($link . $editCourse->image)) {
        unlink($link . $editCourse->image);
    }
    $image = $request->file('file');
    $imageName = Uuid::generate(4)->string . '.' . $image->getClientOriginalExtension();
    $editCourse->image = '/' . $destino . '/' . $imageName;
    $request->file('file')->move($destino, $imageName);
}

我可能做错了什么?

1 个答案:

答案 0 :(得分:1)

您可能需要像这样使用FormData对象:

let data = new FormData();
data.append('file', this.imagen);
// Attach the other properties.
data.append(...);
$inertia.post(data);

这是因为您不应该使用x-www-form-urlencoded上传文件,而应该使用multipart/form-data,它允许您上传二进制数据。这也意味着后端将不再接收JSON字符串,而是接收表单数据响应。 Laravel应该可以自动处理。