0

I'm trying to save an image when updating an item but I'm having trouble sending the file to the controller in order to save it. This is how I'm sending it

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;
        }
    });
},

If I {{imagen}} and {{imageUrl}} in the vue this is the result respectively, this is why I'm sending the imagen and not the url

[object File] 

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

When I Log::info($request) this is the output, when adding a file and changing text and saving,

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,
)  

However if I only add the image and don't change anything else, nothing happens in the Log

Code for updating the image in the controller, in the update function

//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);
}

What could I be doing wrong?

1
  • when sending files you have to use a form data object over a regular json object, check the documentation here and let me know if you have any questions on how to use it developer.mozilla.org/en-US/docs/Web/API/FormData/… Commented Dec 16, 2019 at 15:23

1 Answer 1

1

You likely need to use the FormData object like so:

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

This is because you shouldnt upload files using x-www-form-urlencoded, instead you should be using multipart/form-data which allows you to upload binary data. This also means that the backend will not receive a JSON string anymore, but a form-data response. Laravel should handle this automatically though.

Sign up to request clarification or add additional context in comments.

4 Comments

This is working for me when I change some text and add an image, how could I also fix it where if I only add an image it doesn't save it or even do the log?
not sure what you mean. Also sounds like a different question
It's part of the same question, this solution you gave works but only when the name, description or any other thing apart from the image is also changed, but when I only change or add an image then it doesn't get updated
hard to tell, you could start by simplifying your upload function to if($image = $request->file('file')){...}, and then start debugging where it goes wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.