A guide to downloading files through your web browser

Currently, I am working on a project to download videos from the browser using youtube-dl for educational purposes.

I have encountered an issue regarding downloading local mp4 files in the browser using axios. The download starts successfully; however, after it completes, I am unable to open the mp4 file.

Below is a snippet of my Go code:

func download(w http.ResponseWriter, r *http.Request) {

    fileName := "video.mp4";

    data, err := ioutil.ReadFile(fileName)
    if err != nil {
        log.Print(err)
        return
    }

    w.Header().Set("Content-Type", "application/octet-stream")
    w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
    w.Header().Set("Content-Transfer-Encoding", "binary")
    w.Header().Set("Expires", "0")
    http.ServeContent(w, r, fileName, time.Now(), bytes.NewReader(data))
}

Additionally, here is my JS function that executes when a user inputs text:

<script>
import axios from 'axios';

export default {
  name: 'govideo',

  data() { return {
    url: '',
  } },

  methods: {
    postreq() {
      axios.post("http://127.0.0.1:8090/download", {
        data: this.url,
        responseType: 'blob'
      }).then((response) => {
        var fileURL = window.URL.createObjectURL(new Blob([response.data]));
        var fileLink = document.createElement('a');

        fileLink.href = fileURL;
        fileLink.setAttribute('download', 'video.mp4');
        document.body.appendChild(fileLink);

        fileLink.click();
      })
    }
  }
}
</script>

The issue seems to be with opening the downloaded video file in the browser. Should I consider making a separate get request for it?

Is there something missing or incorrect in my code that could be causing this problem?

Answer №1

Dealing with Axios response handling method is the issue at hand here. I trust that the provided code will assist you in resolving it.

validateGrpc() {
   
    axios.post("http://127.0.0.1:8090/download", {
    data: this.url,
    responseType: 'blob'
  })
          .then(response => {
            var blob = new Blob([response.data]);
            var downloadElement = document.createElement("a");
            var href = window.URL.createObjectURL(blob); //create the download url
            downloadElement.href = href;
            downloadElement.download = "test.mp4"; //the name of the downloaded file
            document.body.appendChild(downloadElement);
            downloadElement.click(); //click to file
            document.body.removeChild(downloadElement); //remove the element 
            window.URL.revokeObjectURL(href); //release the object  of the blob

            //    console.log(response);
          })
          .catch(response => {
            console.log(response);
          });
    }, 

By using my code for downloading files, you will be able to view them directly from your browser. I've checked out your code on GitHub and suggest moving the video.mp4 file into the vue-go-study\backend directory for smooth operation.

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

Pressing the CTRL key and then the PLUS key simultaneously activates the zoom in

Is there a way to capture Ctrl + + / Ctrl + - events in Firefox using the following code: window.onkeydown = function(event) { if(event.ctrlKey && event.keyCode == 61) CtrlPlus(); if(event.ctrlKey && event.keyCode == 169) // or ...

Issue with using Javascript variables within Highcharts

I am facing an issue with displaying a high charts pie chart dynamically. When I pass the exact value format into the data index in the high chart, it doesn't show anything in the chart. However, if I directly assign a value to a variable, it works fi ...

Mastering the placement of script tags in your Next.js application with Next Script

I'm in the process of integrating a third-party script into my Next.js website. This particular script adds an iframe right below its corresponding script tag. Therefore, it is crucial for me to have precise control over the placement of the script ta ...

Stop or terminate all ongoing requests in AngularJS

When switching routes, I want to prevent any pending requests from the previous route in order to avoid issues where responses from the previous route interfere with data on the current route. This sometimes happens when responses from the previous route t ...

Link the getters to the data attribute -> the data attribute remains static

I have a question about assigning getters to my data "lang". Everything seems to be working fine, but I've noticed that when I change the language and the value of my getters changes accordingly, the actual value of my "lang" data does not update. da ...

Update the objects with new values when the user makes changes in the

I am working with dynamically created input fields const [data, setData] = useState({ native: [{}], rolls: [{}] }) // initial data {navtive?.map((item, index) => { return ( <input type="text" name={item.id} ...

Are there any specific plugins or recommended methods for Gatsby to generate each build in a different language?

If I have a website built in Gatsby with English content on www.someWebsiteUrl.com, how can I create the same page with Spanish content on www.someWebsiteUrl.es? Is there a way to specify which site with specific translations should be generated? For exam ...

Challenge: Unable to use import type with element-plus

As a newbie to vite, I have been encountering an issue that I can't seem to resolve despite my efforts in testing and researching on Google. Specifically, when importing the element-plus type in my vite app, such as ElInput... I keep getting this er ...

React Native: Changing Props Triggers Touch Event Cancellation

I am currently utilizing the react-native-gesture-handler library to construct a drag-and-drop sortable array of components. As I progress in the development, I am now focusing on incorporating animations into the functionality. To achieve this, I utilize ...

Locate elements within an array based on certain internal characteristics

I have an array of objects that contain a property called "distributionChannel". I need to find objects within the array that have a value of "sellChannel" for the key in the "distributionChannel" property. Here is my array: [ { "lineItems": [ ...

Looking to update the display of an array received in JSON format and then show it using ng-repeat?

Upon receiving a response from the backend, I am saving it in a variable called "allinfo" in my controller. The data received includes the name, date of birth, and hobby of a person. The hobby is an array that can contain any number of elements. In my vie ...

"Optimize Your Data with PrimeNG's Table Filtering Feature

I'm currently working on implementing a filter table using PrimeNG, but I'm facing an issue with the JSON structure I receive, which has multiple nested levels. Here's an example: { "id": "123", "category": "nice", "place": { "ran ...

Transmit the bound data (using ng-model) to a custom AngularJS directive

/*I am looking to define the maxDate as vmEndDate*/ app.directive('myDatepicker', function ($parse) { return function (scope, element, attrs, controller) { var ngModel = $parse(attrs.ngModel); alert(element.va ...

Dynamic row addition in Material Design Lite table causes format to break

Here's the HTML markup for creating a checkbox using material-design-lite: <label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="checkbox"> <input type="checkbox" id="checkbox" class="mdl-checkbox__input" /> <span c ...

When using angularjs, the $window.location.href may cause the page to load without any

I have a dilemma where I have linked all my CSS and JS files in the index.html file, but subpages are located in a templates directory. When using $window.location.href, only a plain HTML page is returned without any CSS styles. The page renders fine when ...

Audio suddenly no longer working after transferring project to React

View my reproducible example here. This is a demonstration of the issue I am facing. Previously, when the page consisted only of static html with javascript, the sounds were functioning correctly. However, after refactoring into a React app, the sounds ha ...

Is there a way to retrieve all documents based on the start and end of a specific day?

One common issue I am facing involves submitting a date to my nodejs server in a specific format

 2018-11-02T00:36:00+05:30 // The actual time should be 12:36AM However, when examining the document in my database (using studio 3T), the format appear ...

Is it possible to make changes to dynamically inserted HTML using jQuery.ajax?

I'm facing a scenario in jQuery where I make an ajax call that inserts HTML into my website. However, I also need to perform operations on this inserted HTML within the same ajax call's success callback function. Here is a simplified version of ...

The getUserMedia() function fails to work properly when being loaded through an Ajax request

When the script navigator.getUserMedia() is executed through regular browser loading (not ajax), it works perfectly: <script> if(navigator.getUserMedia) { navigator.getUserMedia({audio: true}, startUserMedia, function(e) { __ ...

Is it possible to use JavaScript to upload and manipulate multiple HTML files, replacing text within them to create new output HTML pages?

Is it possible to modify the following code to accept multiple files, process them, and then return the output? <html> <head> </head> <body> <div> <label for="text">Choose file</label> <inp ...