What is the best way to manage files in Vue.js?

I am faced with a challenge in storing image files and video files as Blob data.

One thing I like is that the uploaded video and image files display instantly, which is pretty cool.

I'm not entirely sure if the code below is correct - how can I navigate around this issue? My tech stack includes VueJs and Laravel.

Additionally, when I call the reset method on the addMessage function, it prevents the subsequent addition of another file. Could this be the right place to call it?

Here is the script in my Vue component:

<script>
import { Datetime } from 'vue-datetime';

export default {
    components: { Datetime },

    data() {
        return {
            text: '',
            imageUrl: '',
            imageBlob: '',
            videoUrl: '',
            videoBlob: '',
            startTime: '',
            endTime: '',
        }
    },

    methods: {
        reset(){
            this.text = '';
            this.imageUrl = '';
            this.imageBlob = '';
            this.videoUrl = '';
            this.videoBlob = '';
            this.startTime = '';
            this.endTime = '';
        },

        refreshImage() {
            let comp = this;
            this.readObjectUrl($('#input-image').get(0), function (url, blob) {
                comp.imageUrl = url;
                comp.imageBlob = blob;
            });
        },

        refreshVideo() {
            let comp = this;
            this.readObjectUrl($('#input-video').get(0), function (url, blob) {
                comp.videoUrl = url;
                comp.videoBlob = blob;
                comp.playVideo(url);
            });
        },

        playVideo(url) {
            let video = $('#video-preview').get(0);
            video.preload = 'metadata';
            // Load video in Safari / IE11
            if (url) {
                video.muted = false;
                video.playsInline = true;
                video.play();
            }
        },

        addMessage() {
            this.$emit('added-message', this);
            this.reset();

        },

        readDataUrl(input, callback) {
            if (input.files && input.files[0]) {
                let fileReader = new FileReader();
                fileReader.onload = function () {
                    callback(fileReader.result);
                };
                fileReader.readAsDataURL(input.files[0]);
            }
            else {
                callback(null);
            }
        },

        readObjectUrl(input, callback) {
            if (input.files && input.files[0]) {
                let fileReader = new FileReader();
                fileReader.onload = function () {
                    let blob = new Blob([fileReader.result], {type: input.files[0].type});
                    let url = URL.createObjectURL(blob);
                    callback(url, blob);
                };
                fileReader.readAsArrayBuffer(input.files[0]);
            }
            else {
                callback(null);
            }

        },

    }

}

Everything seems to work fine except for the file uploading functionality.

Thank you for your help!

Answer №1

If you're unsure about what you want to accomplish, consider utilizing Laravel - Storage to store files.

Include an axios post method in your vue.js file to transmit the uploaded files and then utilize storage to save them in the controller.

For instance:

  • Place input fields within an html form named <form name='imageForm'>

  • Create a folder called storage/app/images

In Vue:

let form = document.forms.namedItem('imageForm');
let formData = new FormData(form);

axios.post('/uploads', formData)
        .then(response => {
            console.log('success')
        })

In your controller:

public function store(Request $request) {
        // Validate file upload
        $this->validate($request, [
            'image' => 'required|file'
        ]);

        // Define a filename with the appropriate extension
        $fileExt = $request->image->extension();
        $imageName = "SampleImage" . $fileExt;

        // Save the file in storage
        $imagePath = $request->image->storeAs('images', $imageName);

        // Store the filename in the database for future retrieval (e.g., Order 1 in this example)
        $currentOrder = Order::find(1);
        $currentOrder->image = $imageName;
        $currentOrder->save();
    }

Set up a route with a wildcard (e.g., /uploads/{{image}})

Then use the following controller method to retrieve it:

public function show($image) {
        return Storage::disk('local')->get('images/' . $image);
    }

Let me know if this guidance assists you!

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

Nuxt 3: Leveraging SSR for Client-Side Data Refetching with useFetch

My current project involves building a simple SSR site with the help of useFetch. Everything runs smoothly when I hardcode the URL, but once I switch to using a runtime config variable (from the .env file), the fetch operation works on the server side with ...

Update the information within the Nuxt.js middleware

Can the response content be altered through middleware without changing the URL of the page? I want to clarify that I am not looking to redirect to a different route. ...

Issues with CreateJS chained animations failing to reach their intended target positions

Currently, I am tackling a project that involves using Three.js and CreateJS. However, I have encountered an issue with the animations when trying to move the same object multiple times. The initial animation fails to reach the target position, causing sub ...

Retrieve information according to the object ID with AngularJS UI-Router and $stateParams

I have a unique application that directs to a custom URL based on a specific employee ID parameter when an individual employee is clicked in a list. Upon clicking the employee, users are redirected to a detailed employee page with their ID property as a pa ...

subscribing to multiple observables, such as an observable being nested within another observable related to HTTP requests

Hello, I recently started learning Angular and I am facing a challenge with posting and getting data at the same time. I am currently using the map function and subscribing to the observable while also having an outer observable subscribed in my component. ...

Exploring the power of Vue3 with reactive nested objects and the inclusion of

It seems like I've encountered a bit of a challenge... Perhaps a bug in Vue3 with Typescript and the composition API, or maybe I'm missing something. I'm facing an issue where I'm not getting any intellisense in my IDE (Webstorm) when ...

The click event fails to trigger while trying to parse external HTML

Currently, I am working on a project that requires me to load HTML from an external file and insert it into an existing div element. Although the process is successful overall, I have encountered an issue where the .click() events do not trigger when click ...

Unable to alphabetically arrange buttons automatically

I am encountering a challenge with automatically sorting buttons alphabetically on my webpage. I am unable to determine the method for sorting these buttons using jquery or javascript, but my goal is to have them sorted automatically when the page loads. I ...

The function responsiveTable does not exist

I recently added the following code to my aspx page: <script src="../Scripts/jquery.responsivetable.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#grdStudent').responsiveTable( ...

Having trouble with fetch() not working in Next.JS while securing API Routes with auth.js

Currently, I am working on a project that involves user authentication using auth.js in next.js. The main goal is to create an API that retrieves specific user information from a MongoDB Database. The website itself is secured with middleware in next.js. I ...

iOS hover menu behavior: Close dropdown when the same element is tapped again on iPads

The navigation bar features categories such as: politics, economy, education Upon clicking on these categories, a dropdown menu appears with locations like: asia, europe, North America What I am looking for is this: If the user clicks (tabs) or hovers (o ...

Utilizing fibrous in node.js to efficiently fetch data from the request library

I am struggling to efficiently utilize the fibrous library in conjunction with request for obtaining the body of an HTTP request synchronously. However, I have encountered difficulties in managing the flow. In order to address this issue, I created a simp ...

Can you place more than one Twitter Bootstrap carousel on a single webpage?

Latest Version of Twitter Bootstrap: 2.0.3 Sample HTML Code: <!DOCTYPE html> <html dir="ltr" lang="en-US" xmlns:og="http://opengraphprotocol.org/schema/"> <head> <link rel="stylesheet" type="text/css" media="all" href="reddlec/style. ...

extract elements from dataset

Attempting to splice an array but encountering index issues var kode_pelayanan = []; function deleteKodePelayanan(index){ kode_pelayanan.splice(index, 1); console.log(kode_pelayanan); } Experimented in the console with an array for kode_pelayanan ...

Harnessing the power of express middleware to seamlessly transfer res.local data to various routes

I am in the process of implementing a security check middleware that will be executed on the specific routes where I include it. Custom Middleware Implementation function SecurityCheckHelper(req, res, next){ apiKey = req.query.apiKey; security.securi ...

Unable to navigate to the frame within the Salesforce Lightning interface

Attached below is the screenshot and code that I have used: driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(@title,'Deploy Data Set')]"))); <div class="slds-template_iframe slds-card" force-aloha-page_aloha-page=""> ...

express node struggling to locate bootstrap.js file

I am working with a specific directory structure within my project: projectName | -.sencha/ | - app/ | - view | - controller | - store | - saas | - server/ | -server.js ...

The information sent via POST (via fetch JavaScript with PHP8) is not being received by PHP8

My PHP8 server is not receiving the data I am sending. When trying to insert a new song into my API, an error occurs and in the console, I see an object with POST as an empty array. fetch("http://localhost/api.audio-player/",{ method: 'POST&apos ...

Tips for executing multiple commands in NodeJS using child_process.exec

NOTE: I checked this question but it didn't provide the answer I needed. In my attempt to design a task runner for Atom, I encountered difficulties when trying to execute multi-line shell scripts. The issue arose when executing the following code: co ...

An unexpected error has occurred in the browser console: The character '@' is not valid

I recently made the decision to dive into learning about Unit Testing with JavaScript. To aid in this process, I started using both Mocha.js and Chai.js frameworks. I downloaded the latest versions of these frameworks onto my index.html from cdnjs.com. How ...