
Herunterladen und Streamen von Dateien von URLs in ASP.NET
In ASP.NET können Streaming-Dateien, die zum Speichern von Eingabeaufforderungen im Browser führen, sein wird mit Server.MapPath erreicht. Wenn sich die Datei jedoch in einem virtuell zugeordneten Verzeichnis befindet, funktioniert diese Methode möglicherweise nicht. Hier ist eine alternative Lösung, die HttpWebRequest verwendet, um Dateien von URLs zu streamen:
//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
{
//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 = MediaTypeNames.Application.Octet;
//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();
}
}Mit diesem Code können Sie eine URL für die Datei angeben, die sich überall befinden kann, unabhängig vom physischen Standort der Website. Es richtet die entsprechenden Header ein und streamt die Datei in Blöcken an den Client, sodass ein nahtloses Download-Erlebnis gewährleistet ist.
Das obige ist der detaillierte Inhalt vonWie streame ich Dateien von URLs in ASP.NET?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!
Der Zweck von memcpy in c
Sonst-Verwendung in der Python-Schleifenstruktur
So kaufen und verkaufen Sie Bitcoin auf Binance
Inländische Bitcoin-Kauf- und Verkaufsplattform
Ist OuYi Exchange legal?
Häufig verwendete Linux-Befehle
So erstellen Sie ein rundes Bild in ppt
Was ist der Unterschied zwischen Ibatis und Mybatis?