Instructions on how to use WebClient in C# to download an image and retrieve it from an ASPX page using JavaScript

I have been searching for solutions to this question everywhere, but none of them seem to work for me.

The goal is to download an image from the internet using an aspx page. I want to call the aspx page from JavaScript, retrieve the data, and display it in an Image element. However, I haven't had any luck with that so far.

Here is what I am currently attempting:

System.Net.WebClient wc = new System.Net.WebClient();
byte[] data = wc.DownloadData("http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg");
Context.Response.Clear();
Context.Response.ContentType = "image/JPEG";
Context.Response.OutputStream.Write(data, 0, data.Length);
Context.Response.Flush();
Context.Response.Close();
Context.Response.End();

In JavaScript:

var url = "GetHotlink.aspx";
var tmptxt = call_genpic(url);          // call server with filename and minimum layer value.
var imageObj = new Image();
imageObj.setAttribute('src', 'data:image/jpeg;base64,' + tmptxt);
document.body.appendChild(imageObj);


function call_genpic(url) {
    var reqObj = createRequest();
    reqObj.onreadystatechange = function () {
        if (reqObj.readyState == 4) {
            //callback  
        }
    }
    reqObj.open("GET", url, false);
    reqObj.send(null);
    var V = "";
    V = reqObj.responseText;
    return V;
    return(reqObj.responseText);
}

Although I receive a substantial amount of data from the server when calling the aspx page, the image displayed on the page appears as a broken icon instead of Darth Vader. It seems like there might be an issue with the format or headers along the way. Any suggestions?

Answer №1

It seems like you are using base64 data as the image source, but you are not encoding your response as a base64 string. I recommend using this method to convert the byte array to a string and serve it back to the client as a string instead of binary data.

Your JavaScript code appears to be disorganized. Why do you have two returns one after another? I suggest creating the image and setting its data in the callback function, right where you have a comment.

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

Template repetition in Polymer JS not rendering array properly in Chrome browser

I can't seem to get this code to work properly. <template repeat="{{item in list}}"> </template> Although, I have also attempted the following method which resulted in errors: <template is="dom-repeat" id="example" items="{{list}}"&g ...

Mastering sorting in AngularJS: ascending or descending, the choice is yours!

I have set up a table view with infinite scroll functionality. The table contains 2000 objects, but only shows 25 at a time. As the user scrolls to the bottom, it loads an additional 25 elements and so on. There is a "V" or "^" button in the header that sh ...

Improving efficiency of basic image carousel in Angular 8

In my Angular 8 app, I am developing a basic carousel without relying on external libraries like jQuery or NgB. Instead, I opted to use pure JS for the task. However, the code seems quite cumbersome and I believe there must be a more efficient way to achie ...

What is the best way to extract a value from a URL using JavaScript?

http://localhost:3000/admin/parking/airportParkingPriorityUpdate/xyz Is there a way to extract the value "XYZ" from the URL using JavaScript? ...

Vue.js: Synchronization of props may not happen instantly

Struggling with using vue.js to synchronize a prop between parent and child components. The challenge is that sync relies on events, so every time I update the value, I have to wait for $nextTick before seeing the update. It's cumbersome to include $n ...

Use both a PayPal form and a PHP form simultaneously by implementing a single button that can submit both forms with the help of jQuery and AJAX

While I have a good grasp on HTML and PHP, my knowledge of jQuery and Ajax is quite limited. After spending a significant amount of time searching for answers here: One form, One submission button, but TWO actions and here : Writing to my DB and submittin ...

How to Safeguard Data in FormView on ASP.NET to Prevent Loss?

I am currently working on an ASP.NET application that includes a lengthy FormView for creating or updating jobs. One concern our customer has is the possibility of data loss if users forget to click 'Save' after making changes on the form. We hav ...

Utilizing MATLAB's built-in functions within C#

I need to apply 2D-DCT on a data array collected from image pixels. I previously attempted to use Accord.Math, but found it too slow to work with and the values generated were inconsistent compared to MATLAB values. This is concerning as I also need to ap ...

Implement various authorization attributes on controllers to allow access to the same functionality across diverse settings

Having developed an ASP.NET MVC website, I have primarily used Authorize attributes on my controllers to enforce forms authentication. Now, I am looking to integrate this website with Facebook through a Facebook app. However, for my Facebook users, I want ...

"Unleashing the Power of Effortless Object Unwr

Looking for a better way to convert a raw json snapshot from Firebase into a JS class. My current method is lengthy and inefficient. Does anyone have a more optimal solution? Class: class SuggestedLocation { country_slug region_slug slug marker_ty ...

Managing session IDs in PHP after a successful login to dynamically update the menu bar option from "login" to "logout"

On my website, you will find a menubar with five menus: HOME, DATA, FEEDBACK, ABOUT, and LOGIN. I want to be able to log in by clicking on the login menu (a jQuery modal window pops up for logging in), and after successfully logging in, I would like the ...

Which is more recommended to use in AJAX (XMLHttpRequest) - eventListener or readyStateChange method?

As I revisited a video from WWDC12 discussing advanced effects with HTML5, I couldn't help but notice that for the demo they utilized req.addEventListener("load",callback,true) instead of the usual onreadystatechange. This made me wonder: what differ ...

How can JavaScript be used to apply CSS formatting to text that appears as a new HTML element?

It's unclear if the question accurately reflects what I want to achieve. If I have a form that fades out and is then determined whether to display again through a cookie, can the confirmation message be styled using CSS? For example, I would like to ...

How can a groovy script help in extracting the Version Number using Parse()?

Seeking guidance on parsing a version number using a groovy script When extracting a payload from Ariba, encountering an issue with the ItemNumber field Initially, it parsed as a float, but now returning a version instead Struggling to update this part ...

Enhance the appearance of Ionic popups

Can someone help me with resizing a pop up? I've been struggling to get it right. This is the popup template in question: <ion-view> <ion-content scroll="false" class=""> test </ion-content> < ...

An error occurred in the defer callback: The specified template "wiki" does not exist

I recently developed a Meteor package called Wiki. Within the package, I included a wiki.html file that contains: <template name="wiki"> FULL WIKI UI CODE HERE </template> Next, I created a wiki.js file where I defined my collections and eve ...

Run JavaScript code that has been fetched using AJAX

I am currently working on dynamically updating a javascript array based on data returned from an ajax call. Here is the code I have been using: function makeAjaxCall(data) { xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST", "ShowBusiness", fals ...

Guide to implementing jQuery UI button to an HTML button within an ASP.NET application

My GridView contains a button named btnShowTradeScreenshot. I am looking to apply jQuery buttons to the many buttons created within the GridView. Here is the relevant code snippet from my GridView: <asp:GridView ID="grdTrades" runat="server" ...

Is there a way to access and modify files stored locally through a webpage using HTML?

My team uses a specific application and I need to access a local log that they generate. The goal is to transfer this log to a central system for tracking their activities. To accomplish this, I plan to create a background web application or webpage that a ...

Building a navigable tree structure using a recursive list in C# ASP.NET

I am looking to create a treeview using a recursive list structure. Each item in the list can also contain a list of child items, and this can go on indefinitely with no limit on the number or levels of child nodes. Below is an example of the class struct ...