To download an image from a server URL using Axios and JavaScript in a Vue.js project, you can follow these steps:
Step 1: Set up a new Vue.js project.
Create a new HTML file (e.g., index.html
) and include the Vue.js CDN by adding the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!DOCTYPE html> <html> <head> <title>Download Image using Vue.js</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <button @click="downloadImage">Download Image</button> </div> <script src="app.js"></script> </body> </html> |
Step 2: Create a JavaScript file.
Create a new JavaScript file named app.js
in the same directory as your HTML file and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
new Vue({ el: '#app', methods: { downloadImage() { const imageUrl = 'https://example.com/image.jpg'; // Replace with your server image URL axios .get(imageUrl, { responseType: 'blob' }) .then(response => { const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', 'image.jpg'); document.body.appendChild(link); link.click(); }) .catch(error => { console.error('Error:', error); }); }, }, }); |
In the JavaScript code above, we create a new Vue instance and define a downloadImage
method. Inside the method, we specify the URL of the image you want to download by replacing 'https://example.com/image.jpg'
with the actual URL.
We use Axios to make a GET request to the image URL with the responseType
set to 'blob'
. This ensures that the response is treated as binary data.
Once the response is received, we create a URL for the image blob using window.URL.createObjectURL()
. Then, we create a new <a>
element, set its href
attribute to the blob URL, and specify the download
attribute with the desired file name ('image.jpg'
in this example). Finally, we append the <a>
element to the document body and trigger a click event on it programmatically using link.click()
, which initiates the download.
Step 3: Open the HTML file in a web browser.
Save both the HTML and JavaScript files in the same directory. Open the HTML file in a web browser, and when you click the “Download Image” button, the image will be downloaded to your device.
That’s it! You have created a Vue.js project that allows you to download an image from a server URL using Axios and JavaScript.