C# 如何在asp.net web应用程序中使用Url从我的服务器下载jpg/doc文件
我的问题是无法从服务器下载文件 我的代码适用于任何Google图像url(例如:-) 但对于我的服务器图像url(“例如:-[http://110.15.445.87/xyz/abc/123.jpg])) 我不知道问题出在哪里 我的代码是:-C# 如何在asp.net web应用程序中使用Url从我的服务器下载jpg/doc文件,c#,asp.net,C#,Asp.net,我的问题是无法从服务器下载文件 我的代码适用于任何Google图像url(例如:-) 但对于我的服务器图像url(“例如:-[http://110.15.445.87/xyz/abc/123.jpg])) 我不知道问题出在哪里 我的代码是:- //Create a stream for the file Stream stream = null; //This controls how many bytes to read at a time and send to
//Create a stream for the file
Stream stream = null;
//This controls how many bytes to read at a time and send to the client
int bytesToRead = 10000;
// Buffer to read bytes in chunk size specified above
byte[] buffer = new Byte[bytesToRead];
// The number of bytes read
try
{
String Url = "http://112.196.32.51/ll1/UploadFiles/13062402231250.jpg";
//String Url = "http://blogs.independent.co.uk/wp-content/uploads/2012/12/google-zip.jpg";
//Create a WebRequest to get the file
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(Url);
//Create a response for this request
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
//Get the Stream returned from the response
stream = fileResp.GetResponseStream();
// prepare the response to the client. resp is the client Response
var resp = HttpContext.Current.Response;
//Indicate the type of data being sent
resp.ContentType = "application/octet-stream";
String fileName = "Rock.jpg";
//Name the file
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
// Verify that the client is connected.
if (resp.IsClientConnected)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length);
// Flush the data
resp.Flush();
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
}
什么不起作用?您是否收到错误消息?与其自己编写所有代码,不如直接对图像url执行301重定向,让asp.net引擎处理响应内容类型?@YuriyGalanter先生,在我的severurl情况下,“保存/打开”对话框未打开。