简体   繁体   English

如何使用WebClient在C#中下载图像并使用Javascript从ASPX页面获取图像

[英]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. 该代码的目的是让我可以通过aspx页面从互联网下载图像。 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. 因此,从Javascript开始,我将调用aspx页面,该页面应提供数据,然后将其提供给Image元素,但到目前为止没有骰子。

I'm currenty trying: in GetHotlink.aspx page: 我目前正在尝试:在GetHotlink.aspx页面中:

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: 并在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. 我可以看到,当我调用aspx页面时,正在从服务器获取大量数据,但是添加到DOM的图像显示为残破的图像图标。 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. 您正在使用base64数据作为图像源,但未将响应编码为base64字符串。 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. 此外,您的JavaScript代码看上去也一团糟。 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) 您应该创建图像并将其数据设置在回调中(在有注释的位置)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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