Web Service上传下载文件[2]

[入库:2005年8月18日] [更新:2007年3月25日]

本文简介:选择自 cloud_soft 的 blog

我们要进行处理的是在后代码里面,下面详细的介绍,upload.aspx.cs:

using system; using system.collections; using system.componentmodel; using system.data; using system.drawing; using system.web; using system.web.sessionstate; using system.web.ui; using system.web.ui.webcontrols; using system.web.ui.htmlcontrols; using system.web.services; using system.io; namespace aspxwebcs { /// <summary> /// upload 的摘要说明。 /// 利用该方法通过web services上载文件 /// </summary> public class upload : system.web.ui.page { protected system.web.ui.htmlcontrols.htmlinputfile myfile; protected system.web.ui.webcontrols.button button1; private void page_load(object sender, system.eventargs e) { // 在此处放置用户代码以初始化页面 } #region web form designer generated code override protected void oninit(eventargs e) { // // codegen:该调用是 asp.net web 窗体设计器所必需的。 // initializecomponent(); base.oninit(e); } /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void initializecomponent() { this.button1.click += new system.eventhandler(this.button1_click); this.load += new system.eventhandler(this.page_load); } #endregion private void button1_click(object sender, system.eventargs e) { ///首先得到上载文件信息和文件流 if(myfile.postedfile != null) { system.web.httpfilecollection ofiles; ofiles = system.web.httpcontext.current.request.files; if(ofiles.count < 1) { response.write ("请选择文件。"); response.end(); } string filepath = ofiles[0].filename; if(filepath == "" || filepath == null) { response.write ("请选择一个文件。"); response.end(); } string filename = filepath.substring(filepath.lastindexof("\\")+1); try { ///处理上载的文件流信息。 byte[] b = new byte[ofiles[0].contentlength]; system.io.stream fs; xml.sz.luohuedu.net.aspxwebcs.upload o; o = new xml.sz.luohuedu.net.aspxwebcs.upload(); fs = (system.io.stream)ofiles[0].inputstream; fs.read(b, 0, ofiles[0].contentlength); ///调用web services的uploadfile方法进行上载文件。 response.write(o.uploadfile(b, filename)); fs.close(); } catch(exception ex) { response.write(ex.message); } } else { response.write("请选择文件"); } } } }

最后,需要注意的是:在保存文件时,您应该确保指定文件的完整路径(例如,"c:\myfiles\picture.jpg"),并确保为 asp.net 使用的帐户提供要存储文件的目录的写权限。上载大文件时,可使用 元素的 maxrequestlength 属性来增加文件大小的最大允许值,例如:

<configuration> <system.web> <httpruntime maxrequestlength="1048576" executiontimeout="3600" /> </system.web> </configuration>

其中:maxrequestlength:指示 asp.net 支持的http方式上载的最大字节数。该限制可用于防止因用户将大量文件传递到该服务器而导致的拒绝服务攻击。指定的大小以 kb 为单位。默认值为 4096 kb (4 mb)。executiontimeout:指示在被 asp.net 自动关闭前,允许执行请求的最大秒数。在当文件超出指定的大小时,如果浏览器中会产生 dns 错误或者出现服务不可得到的情况,也请修改以上的配置,把配置数加大。

另外,上载大文件时,还可能会收到以下错误信息:

aspnet_wp.exe (pid: 1520) 被回收,因为内存消耗超过了 460 mb(可用 ram 的百分之 60)。

如果遇到此错误信息,请增加应用程序的 web.config 文件的 元素中 memorylimit 属性的值。例如:

<configuration> <system.web> <processmodel memorylimit="80"/> </system.web> </configuration>

我在自己的机器上测试,可以上传50m以上的文件。以上代码在windows xp + .net 1.0 + vs.net2002下测试通过。

本文关键:Web Service上传下载文件
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top