简体   繁体   中英

How to Download image in c# using webclient and use Javascript to get image from aspx page

I've seen fragments of various answers to this questions here and there, and I can't get any of them to work.

The purpose of the code is so I can download an image from the internet via an aspx page. so from Javascript, I'll call the aspx page, which should serve up the data, which I then feed into an Image element, but so far no dice.

I'm currenty trying: in GetHotlink.aspx page:

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();

and 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);
}

I can see that I'm getting a nice chunk of data back from the server when I call the aspx page, but the image that I add to the DOM comes up as the broken image icon. No Darth Vader! I suspect that somewhere along the way Darth is getting into the wrong format, or is getting the wrong header or so. Any ideas?

You are using base64 data as your image source but you are not encoding your response as base64 string. Use this method to convert the byte array to string and serve it back to the client as string not as binary data.

Also your JavaScript code looks all messed up. Why do you have two returns one after another. You should create the image and set its data in the callback (right where you have a comment)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM