File not being retrieved by FormData Object

Currently, I am in the process of developing an avatar editor based on the instructional content provided in the Build a Forum video series.

My development environment is set up with Laravel version 5.8.34.

Upon inspecting the console.log output from the #handleFileUpload(e)# method, it shows that the uploaded file is being processed successfully.

The uploaded image displays correctly on the page as intended.

However, when reviewing the console.log output from the #persist(file)# method, it indicates that an empty object is being passed through.

The data FormData {} also seems to be missing crucial information.

Unfortunately, despite the successful upload and display of the image, the persistence of this uploaded data does not seem to be executing properly.

This is the code snippet from my Controller Method:

public function avatar_upload($id)
    {
        $validate = request()->validate([
            'avatar' => ['required', 'image']
        ]);

        $emp = Employee::with('user')->where('user_id', $id)->first();
        $avatar = $emp->user->firstName . $emp->user->lastName . '.png';

        Storage::disk('spaces')
            ->putFileAs('avatars', request()->file('avatar'), $avatar, 'public');

        $emp->avatar = $avatar;
        $emp->save();

        return response([], 204);
    } // end function

This section pertains to My Component:

<template>
    <div>
        <div class="text-center mb-4">

            <div class="flex justify-center font-thin text-grey-dark text-2xl">
                {{user.office}}
            </div>

            <div class="text-center">
                <img class="relative rounded-lg"
                    :src="avatar">
            </div>
            <form @submit.prevent="handleFileUpload"
                  enctype="multipart/form-data"
                  v-if="canEdit">
                <input
                    type="file"
                    name="avatar"
                    ref="file"
                    accept="image/png"
                    class="tw-input"
                    @change="handleFileUpload">
            </form>
        </div>
    </div>
</template>

<script type="text/babel">
    export default {
        name: 'AvatarReplace',
        data() {
            return {
                canEdit: true,
                avatar: this.user.avatar
            };
        },
        props: ['user'],
        methods: {
            handleFileUpload(e) {
                if(! e.target.files.length) { return; } 

                let file = e.target.files[0];
                console.log('FILE', file);

                let reader = new FileReader();

                reader.readAsDataURL(file);

                reader.onload = e => {
                  this.avatar = e.target.result;
                };

                this.persist(file);
            },
            persist(file) {
                let data = new FormData();

                data.append('avatar', file);
                console.log('DATA', data);

                let path = `/api/staff/avatar_upload/${this.user.id}`;
                axios.post(path, data)
                    .then((rsp) => {
                        //console.log(rsp);
                        //this.$toastr.s('File Uploaded');
                    });

            }
        }
    };
</script>

Answer №1

Let's make sure axios recognizes that we are dealing with a non-standard form by specifying the content-type as multipart/form-data

axios.post(path, data, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
}).then((response) => {
   //
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we determine the total number of mandatory fields in an AngularJS form?

Can you explain how to calculate the number of required fields in a form using AngularJS? In my form, there are two required fields (email and select view). I want to display the count on my page - showing 2 if email is filled, 1 if only email is filled, a ...

When making an Ajax request to another website, the response received is in HTML format instead of

I am attempting to retrieve an array by making an AJAX GET request to a URL. Below is my controller code, which is hosted locally at localhost:3000 def merchant_ids merchants = Merchant.where(id: params[:id]).pluck(:merchant_name, :id, :merchant_city, ...

How can we showcase an HTML file in Express by utilizing a POST request?

My objective is to successfully submit my form data and then dynamically navigate to an HTML file where the values are displayed. Here's the code snippet from my app.post function in Express: const results = fs.readFile("order.html", " ...

Utilizing AJAX to Invoke a Method in a CS Page: A Step-By-

I am trying to utilize AJAX to call a method in my CS page. Below is the design code I am using: <!-- Name --> <input type="text" name="name" id="name" required="required" class="form" placeholder="Name" /> <!-- Email --> <input type= ...

json evaluation causing an issue

When trying to use eval for the JSON below, I am encountering a syntax error with the message: Expected ']'. I am unsure of what is missing in my code. Here is my JavaScript statement: eval('var jsonResponse = ('+response+')' ...

Issue with Promise function not resolving in the context of javascript and Wit.ai

Currently, I am in the process of updating the functions in my messenger/wit.ai chat bot to transition from using callbacks to promises. The initial format functions properly: ['buildScenario'](sessionId, context, cb) { var trendChoice = s ...

Refreshing table data in React Js after the expiration of a specific item's valid till date and time

I have a data table with columns labeled Item, Time, and ValidTill. For instance, one of the items has a time of April 2nd 2022, 3:08:01 pm and a ValidTill time of April 2nd 2022, 3:09:26 pm. I currently make an API call in useEffect when the component m ...

Does a React functional component continuously re-render if it contains a child component?

For the past few days, I've been facing a performance issue in a React app (specifically React Native). The core of the problem is this: Whenever a function component Parent has another function component as its Child, the Parent will consistently re ...

Turf.js - Missing type declarations when importing into a Vue/Vite environment

Struggling with Turf.js's bbox functionality. Despite all my efforts, TypeScript type definitions remain elusive. I attempted the following steps: Included in package.json: "dependencies": { ... "@turf/turf": "6.5.0&q ...

Navigating between two table components in React JS

I am a beginner in the world of React and I am struggling with switching between these two tables. Despite consulting the documentation for inline conditional statements, I still couldn't figure it out. My goal is to have the tables switch after click ...

Utilizing JavaScript to read text files and dynamically updating values in the browser instantaneously

Utilizing a JavaScript file, I am able to retrieve the value of a text file and display it on the main HTML page for clients to see. Here is an example of the HTML code: <div class="column"> <div class ="header2"> ...

Maintain an equal distance between 2 out of 3 elements while resizing the window to ensure responsiveness

There are two image divs stacked on top of each other, positioned beside a fluid header logo (.svg) also contained in a div. The HTML: <header class="site-header" role="banner" itemscope="itemscope" itemtype="http://schema.org/WPHeader"><div cla ...

Dynamically import React Material UI Icons when needed

The concept here revolves around importing react material UI icons only when necessary, especially in situations where we may not know the icon name during compile time. (Ensuring that we have valid icon names) My method involved using a require statement ...

Prevent the end of the scroll from causing a new scroll to start?

In the code snippet provided, there are two divs. When scrolling down past the end of the blue div, the overall body/div also scrolls down. Is there a way to prevent this additional scrolling effect once reaching the scroll boundary of the blue div? For e ...

Is it possible to achieve Two-Way Binding in a custom directive without relying on NgModel?

I am creating a custom dropdown without using any input element or ngModel for two-way binding. Is it possible to achieve two-way binding with custom attributes? var mainApp = angular.module('mainApp', []); mainApp.directive('tableDropdo ...

Guidance on Implementing a Delay and FadeIn Effect for AJAX Responses from JSON Iterator

How can I iterate over the following foreach loop with a delay between each item and a fadeIn effect on each? I am debating whether .append() is the most suitable function to use since I want to load a templated div with the class #fan for each person in ...

Tap here to switch between 2 jquery functions

Due to the deprecation of the toggle() method in jQuery version 1.8 and its removal in version 1.9, an alternative approach is needed for versions 1.11 and above. You can check out the documentation for more information. If you are looking to replicate th ...

Using an if statement to run a script in Npm

Is there a way to configure an npm run script to use different AWS accounts based on the environment? { "config": { "acc": if ({npm_config_env} == "dev") "account1" else "account_2" }, "scr ...

Adjusting the positioning of the label in a d3 line graph

Here is the data file named: myStData.csv xindex,mylabel 40,23 41,13 42,12 43,21 44,40 45,50 In this code snippet, the label is currently shown at the "start" position (text-anchor set to start). The label is placed according to the start value in the cs ...

Generate an array by filtering out null properties from a Javascript/Typescript object

I have a TypeScript plain old JavaScript object (POJO) structured as shown below: export interface Items { firstName?: String; lastName?: String; address?: String; phoneNumber?: number; city?: String; stat ...