`
lovnet
  • 浏览: 6710198 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

Response.OutputStream.Write Out of Memory 下载太大的文件的时候,内存使用太多

阅读更多

Solution:

http://www.9iyou.com/Program_Data/ASPNET-27564.html

按字节来取
private void Page_Load(object sender, System.EventArgs e)
{
string strDocDir;
string strFile;
strDocDir="updownload";
strFile=Request.QueryString["strFile"];

System.IO.Stream iStream = null;

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

// Length of the file:
int length;

// Total bytes to read:
long dataToRead;

// Identify the file to download including its path.
string filepath = Server.MapPath(strDocDir) "\\" strFile;

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

// 定义file
System.IO.FileInfo file = new System.IO.FileInfo(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=" System.Web.HttpUtility.UrlEncode(file.Name,System.Text.Encoding.UTF8));

// 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, 300000);

// 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[300000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}

}
Response.Clear();
Response.End();
}
catch (Exception ex)
{
// Trap the error, if any.
Response.Write("Error : " ex.Message);
Response.Clear();
Response.End();
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
Response.Clear();
Response.End();
}
}

==============================================================

http://www.longtailvideo.com/support/forum/Setup-Problems/6804/Using-a-Url-for-the-file-parameter

- Turn the buffer on when trying to do chunking of large files:
thus:
response.buffer = true
at the beginning of the script.

- The pack code in PHP is not needed to create the FLV header but can b created by reading the 13 bytes of data at the beginning of the flv file thus:
If (valPos > 0) Then
Response.BinaryWrite objStream.Read(13)
End if

When looping through the file and streaming the 16384 bytes of data ,if the file is sufficiently large you may run out of memory(buffer) and get errors.I fixed this by flushing the response object each time and clearing the buffer so the buffer did not have more than 16384 bytes at any time.Thus:

do while Not objStream.EOS
Response.BinaryWrite objStream.Read (16384)
Response.Flush
Response.Clear
loop


With this I was finally able to stream even my large file ..... good.The code below is th complete stream.asp, you may want to add it to the stream.asp (zip file) code on your http streaming page for people to try it out and hopefully improve on it.


<%
response.Buffer = true
Response.ContentType = "video/x-flv"
//request position and file name
Dim valPos,valFile
valPos = Request("pos")
valFile = Server.Mappath(Request("file"))

//check whether file type is FLV
If (LCase(Right(valFile,Len(valFile)-InstrRev(valFile,"."))) <> "flv")Then
Response.End
End if
//if position was not passed set pos to 0
If (valPos = "") Then
valPos = 0
End if
//create streaming object
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Open
objStream.Type = 1
objStream.LoadFromFile(valFile)

//if pos is greate than 0 proceed to get FLV header information
If (valPos > 0) Then
Response.BinaryWrite objStream.Read(13)
End if

//set position to begin streaming
objStream.Position = valPos
//loop through file, flush and clear buffer each time
do while Not objStream.EOS
Response.BinaryWrite objStream.Read (163840)
Response.Flush
Response.Clear
loop
//close stream object
objStream.Close
Set objStream = Nothing
%>




The only pain is that this only works for both small and large files on IE, when accessed on Mozilla only the smaller files can be streamed , if you try it on a large file it stops playback.Let me know what your take on that is.

分享到:
评论

相关推荐

    handleStream ServletOutputStream out = response.getOutputStream(); InputStream i

    NULL 博文链接:https://nethub2.iteye.com/blog/2023937

    DotNetBarcode.dll 生成二维码,亲手试过支持中文

    网上有好多都说支持中文,实际都不行 这个是我试过可以支持中文的 代码例子从网上找了个... string code = Request.Params["code"]; DotNetBarcode dnb = new ... img.Save(Response.OutputStream, ImageFormat.Gif);

    SharpMap + ZedGraph 饼图实例,可生成各种统计图

    context.Response.OutputStream.Write(buffer, 0, buffer.Length); public SharpMap.Styles.VectorStyle GetChartingStyle(SharpMap.Data.FeatureDataRow row) { SharpMap.Styles.VectorStyle style = new ...

    Thinking in Java 4th Edition

    of abstraction ........................ 15 An object has an interface ........................... 17 An object provides services ................... 18 The hidden implementation .................... ...

    服务器下载文件

    System.out.println("--下载文件名称--:"+file_unique); System.out.println("----"); System.out.println("--------"); response.addHeader("Content-Disposition","attachment;filename=" + file_unique); ...

    J2ME入门教程.10(j2me与Servlet相互通讯)编写和配置Servlet服务端

    import java.io.*; import java.util.*; import javax.servlet.*; ... public class MyServlet ... OutputStream out_Stream = response.getOutputStream(); out_Stream.write( data ); out_Stream.close(); } }

    java.lang.IllegalStateException: OutputStream already obtain

    NULL 博文链接:https://anminer.iteye.com/blog/845067

    excel文件下载工具类

    java语言,将数据下载导出为excel表格的工具类,实现方式为response.outputStream流;

    通过HttpURLConnection获取SESSIONID

    out.write(parameters.getBytes(),0,parameters.getBytes().length); InputStream in = hc.getInputStream(); InputStreamReader reader = new InputStreamReader(in,"gb2312"); BufferedReader read = ...

    可以显示中文名称的下载组件

    jspsmartupload.jar组件大家都知道,但是它本身自带的download功能并不支持中文名称的文件,在下载的时候会出现乱码,我自己编写了一个FileDownload类,放到了这个jar包中,这个类用的UTF-8编码方式,所以可以对中文...

    使用urlconnection下载文件或图片并保存到本地

    * 使用URLConnection下载文件或图片并保存到本地。 * * @author 老紫竹(laozizhu.com) */ public class URLConnectionDownloader { public static void main(String[] args) throws Exception { ...

    swing导出Excel

    在table中导出Excel详细过程OutputStream os = response.getOutputStream(); response.setContentType("application/msexcel"); response.setHeader("Content-disposition","attachment; filename=clerkAddress.xls...

    批量打包下载

    OutputStream outs = response.getOutputStream();// 获取文件输出IO流 BufferedOutputStream bouts = new BufferedOutputStream(outs); response.setContentType("application/x-download");// 设置response...

    java io InputStream and outputStream

    System.out.println("文件不存在...."); } else { try { InputStream is = new FileInputStream(file1);// 打开文件 byte[] cont = new byte[(int) file1.length()]; is.read(cont);// 读取文件...

    android 上传文件

    System.out.println(response); String[] items = response.split(";"); String id = items[0].substring(items[0].indexOf("=")+1);//服务返回绑定该文件的资源id String position = items[1]....

    验证码下载jsp

    java.io.OutputStream os=response.getOutputStream(); ImageIO.write(image, "JPEG", os); os.flush(); os.close(); os=null; response.flushBuffer(); out.clear(); out = pageContext.pushBody(); %&gt; ...

    poi导出excel所用jar包,可添加至maven仓库,也可以自己配置,适合各种浏览器

    通常业务需求都是客户端一个导出按钮,发送请求到服务端,服务端写一个接口导出报表到客户端,客户可以自行下载。无论Struts或者springMVC均可。 @RequestMapping("Export") @ResponseBody public String getAll...

    strust文件上传

    System.out.println( streamIn.available()+"文件大小byte"); //这个是io包下的上传文件类 File uploadFile = new File(dir); //指定上传文件的位置 if (!uploadFile.exists() || uploadFile == null) { //判断...

    ssh(structs,spring,hibernate)框架中的上传下载

    具体的调用是将Web层将response.getOutputStream()传给write(OutputStream os,String fileId)接口,业务层直接将文件数据输出到这个响应流中。具体实现请参见错误!未找到引用源。节下载文件部分。  2、业务层接口...

    ASP.NET绘图(GDI)

    image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); //注意:这个很关键,没有就不能显示图片。其中ImageFormat取枚举值 image.Dispose(); g.Dispose(); //销毁对象 效果图如下:

Global site tag (gtag.js) - Google Analytics