8

मैं HttpResponse.OutputStream का उपयोग ContentResult के साथ करना चाहता हूं ताकि मैं समय-समय पर Flush कर सकूं ताकि नेट द्वारा बहुत अधिक रैम का उपयोग न किया जा सके।एमवीसी 3 से बहुत अधिक रैम का उपयोग किये बिना बड़े डेटा को सही तरीके से स्ट्रीम कैसे करें?

लेकिन एमवीसी FileStreamResult, EmptyResult, FileResult, ActionResult, ContentResult के साथ सभी उदाहरण दिखाए गए कोड जो सभी डेटा को स्मृति में प्राप्त करते हैं और उनमें से किसी एक को पास करते हैं। इसके अलावा एक पोस्ट का सुझाव है कि लौटने के साथ HttpResponse.OutputStream का उपयोग करना बुरा विचार है। एमवीसी में मैं और कैसे कर सकता हूं?

एमवीसी सर्वर से बड़े डेटा (एचटीएमएल या बाइनरी) के फ्लश करने योग्य आउटपुट को व्यवस्थित करने का सही तरीका क्या है?

EmptyResult या ContentResult या FileStreamResult लौटने का बुरा विचार क्यों है?

+0

क्या किसी के पास http://stackoverflow.com/a/2189635/37055 में उल्लिखित पाइप स्ट्रीम का उपयोग करने पर कोई जानकारी है –

उत्तर

5

यदि आपके पास पहले से काम करने के लिए स्ट्रीम है तो आप FileStreamResult का उपयोग करना चाहेंगे। कई बार आपको फ़ाइल तक पहुंच हो सकती है, एक स्ट्रीम बनाने की आवश्यकता होती है और उसके बाद क्लाइंट को आउटपुट करना पड़ता है।

System.IO.Stream iStream = null; 

// Buffer to read 10K bytes in chunk: 
byte[] buffer = new Byte[10000]; 

// Length of the file: 
int length; 

// Total bytes to read: 
long dataToRead; 

// Identify the file to download including its path. 
string filepath = "DownloadFileName"; 

// Identify the file name. 
string filename = System.IO.Path.GetFileName(filepath); 

try 
{ 
    // Open the file. 
    iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, 
       System.IO.FileAccess.Read,System.IO.FileShare.Read); 


    // Total bytes to read: 
    dataToRead = iStream.Length; 

    Response.ContentType = "application/octet-stream"; 
    Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); 

    // Read the bytes. 
    while (dataToRead > 0) 
    { 
     // Verify that the client is connected. 
     if (Response.IsClientConnected) 
     { 
      // Read the data in buffer. 
      length = iStream.Read(buffer, 0, 10000); 

      // Write the data to the current output stream. 
      Response.OutputStream.Write(buffer, 0, length); 

      // Flush the data to the HTML output. 
      Response.Flush(); 

      buffer= new Byte[10000]; 
      dataToRead = dataToRead - length; 
     } 
     else 
     { 
      //prevent infinite loop if user disconnects 
      dataToRead = -1; 
     } 
    } 
} 
catch (Exception ex) 
{ 
    // Trap the error, if any. 
    Response.Write("Error : " + ex.Message); 
} 
finally 
{ 
    if (iStream != null) 
    { 
     //Close the file. 
     iStream.Close(); 
    } 
    Response.Close(); 
} 

Here माइक्रोसॉफ्ट ऊपर कोड समझा लेख है।

संबंधित मुद्दे