How to fetch and display images using Vue.js with Axios and a web API

I have managed to successfully upload an image using axios and can preview it in Postman. However, I am unsure of how to proceed with rendering the image in vuejs.

Implementing the Get Method:

public HttpResponseMessage FetchImage(int id)
{
    ImageService _imageService = new ImageService(id);
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    string filepath = HostingEnvironment.MapPath("~/App_Data/Images/" + _imageService.GetImageData.image.filename);
    FileStream fileStream = new FileStream(filepath, FileMode.Open);
    Image image = Image.FromStream(fileStream);
    MemoryStream memoryStream = new MemoryStream();
    image.Save(memoryStream, ImageFormat.Jpeg);
    result.Content = new ByteArrayContent(memoryStream.ToArray());
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
    return result;
}

Vuejs Integration:

fetchImage (image) {
    axios({
        method: 'get',
        url: 'http://localhost:20449/api/images',
        headers: {
          'Content-type': 'image/jpeg'
        },
        params: {
          id: image.id
        }
     }).then(response => {
        this.displayedImage = response.data // Unsure if this is correct way             
     })
  },

What approach should I take to render the fetched image in an HTML tag?

Answer №1

I recently discovered a solution that has been effective for me - converting images to base64 format.

Utilizing the HttpGet Method

public string Process(int id)
{
    ProcessService _ProcessService = new ProcessService(id);
    string filepath = HostingEnvironment.MapPath("~/App_Data/Uploads/" + 
    _ProcessService.GetStepWithProject.process.filename);
     byte[] imageArray = System.IO.File.ReadAllBytes(filepath);
     string base64ImageRepresentation = Convert.ToBase64String(imageArray);
     return base64ImageRepresentation;
}

Implementation in Vue Template

<img :src="image" alt="Base64 encoded image" />

Using Axios Function

fetchAdditionalInfo (process) {
    this.image = ''
    axios({
        method: 'get',
        url: 'http://localhost:20449/api/processes',
        headers: {
          'Content-type': 'image/jpeg'
        },
        params: {
          id: process.id
        }
     }).then(response => {
        this.image = 'data:image/jpg;base64,'.concat(this.image.concat(response.data))            
     })
  },

export default {
    data () {
        image: ''
    }
}

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

Update my function to be asynchronous by changing async: false to async: true using JQuery and Ajax

I've created a function in a JavaScript class that accesses a PHP file to retrieve information from a database. Although this function works well, I attempted to set the property async: true, and it caused the function to stop working. (I received th ...

What is the purpose of defining the initialState in Redux?

As per the Redux documentation, it is considered a best practice to establish an initialState for your reducer. However, maintaining this initialState can become challenging when the state relies on data from an API response, leading to discrepancies betwe ...

Click to Rotate the Shape

I am attempting to apply a rotation effect on a shape when clicked using jQuery and CSS. My goal is to select the element with the id of x and toggle the class rotate on and off. The rotate class utilizes the CSS transform property to achieve the desired r ...

I'm trying to figure out how to switch the Heroes array to the res array while utilizing the react useState hook. It's been successful in my past projects, but for some reason,

const [Heroes, setHeroes] = useState([]) useEffect(() => { API.findFavorites().then((res) => { console.log(res) setHeroes([...Heroes, res]); console.log(Heroes) }) }, []); I am struggling ...

I am experiencing an issue where components are constantly re-rendering whenever I type something. However, I would like them to

Currently, I am in the process of developing a REACT application that takes two names, calculates a percentage and then generates a poem based on that percentage. The issue I am facing is that whenever I start typing in the input fields, the LovePercentCon ...

Select elements in jQuery using both a specific selector and a negative selector

I am currently working with a JQuery function that highlights a specific word and scrolls to it: $('article.node--article p, .video-title').highlightWordAndScroll({ words : search_word, tag : '<span class="found_key ...

What is causing this to function properly on Firefox but not on Chrome or IE?

After clicking the process_2banner button on my html page, a piece of code is executed. Surprisingly, this code performs as expected in Firefox, but not in Chrome or Internet Explorer. In those browsers, although the ajax code is triggered, the div spinner ...

Is it possible to quickly sync API data with a CSV file for updates?

My unique code allows retrieving Amazon product prices with the ASIN (Amazon Standard Identification Number). Here is the code snippet for reference. <?php class AmazonAPI { // Code implementation details here } ?> To display the price, use ...

Utilizing Chart.js to visualize live data from a dynamic MySQL dataset

Struggling to create a dynamic dataset for my Chart.js project, specifically with the data obtained from getpromorevenuechart.php. Here's an example of the dataset: [{"mmyy":"2019-12","promocode":"promo1","amount":"2776"},{"mmyy":"2020-01","promocode ...

Struggling to reveal concealed items on a webpage using jQuery and attempting to cycle through an array without success

Looking to display or hide certain sections on a page based on specific conditions. I want to only show the sections of the page that contain words from the conditionsToShow array. function hideWorkflowConditions() { // initially hide the elements ...

Error: Access Denied - discord.js bot command cannot be executed due to lack of authorization

Every time I initiate the bot and try to execute my "ping" command, an error occurs: js:350 throw new DiscordAPIError(data, res.status, request); ^ DiscordAPIError: Missing Access at RequestHandler.execute (C: ...

Mastering the Art of SQL Submission with PHP Ajax Requests

I've encountered an issue with a form that, upon validation, triggers two Ajax requests before submitting the data to create an entry in a MySQL database. The Ajax requests generate URLs to Google Documents using upload.php. However, when certain unk ...

Waiting for an Element to Become Visible in Selenium-Webdriver Using Javascript

When using selenium-webdriver (api docs here), how can you ensure that an element is visible before proceeding? Within a set of custom testing helpers, there are two functions provided. The first function successfully waits for an element to exist, howeve ...

Displaying .aspx within a Panel or UpdatePanel

Currently, I am in the process of developing a web-based game using ASP.NET and C#. Initially, I was structuring the different game screens (start, hi-score, results) as separate Panels nested within a main UpdatePanel. However, with the realization that t ...

Dealing with a JavaScript Problem on Wordpress Using AJAX

Struggling with transitioning a website from Drupal to WordPress, I encountered an issue with a page that utilizes AJAX. A user followed a tutorial on implementing AJAX using JavaScript, PHP, and MySQL. Even though the AJAX functionality works fine on Drup ...

I am having trouble retrieving images on my website and displaying URL images

Every time I attempt to retrieve an image URL from the database for the client, I encounter the following error: Refused to load the image 'https://nuclear-photos.s3-ap-southeast-1.amazonaws.com/…22:33:44%20GMT+0400%20(GST)TEST.png' because i ...

Picking a Random Row Number

I am currently developing a website that selects employees at random for drug testing. I am working on creating a report/code using SQL Server 2008, ASP.NET, and C#. Here is a snippet of the progress I have made: I am looking to generate a report that list ...

Implementing bbcode feature in TinyMCE

Take a look at the custom html code provided below: <button type="button" class="btn btn-default btn-sm" onclick="appendBBCode('youtube','ContentArea')">[youtube]</button> <br> <div class="form-group field-boats-co ...

Implementing Dynamic Styling Using Parent Component in React Native

I am facing an issue with a <Text> component that is receiving a style through props... TextFile.js: <Text style={styles.text}> This is a line of text and this might be a second line </Text> screenFile.js: <View style={styles.v ...

Eliminate repetitive elements within an array of objects

Is there a way to eliminate duplicate values in an object array using Javascript? 0: {d: “2021/01/19”, color: “#009988"} 1: {d: “2021/01/19”, color: “#CC3311"} 2: {d: “2021/01/19”, color: “#009988"} 3: {d: “2021/01/19”, ...