asp.net 包含两个控件可以使用户向网页服务器上传文件。一旦服务器接受了上传的文件数据,那么应用程序就可以进行保存,进行检查或者忽略它。
- htmlinputfile - html 服务器控件
- fileupload - asp.net 网页控件
两种控件都允许文件上传,但是 fileupload 控件自动设置编码格式,然而 htmlinputfile 控件并不会这样。
1、使用htmlinputfile文件上传
前台
<form enctype="multipart/form- data"> <input type="file" name="myfile"/> </form>
后台:
//上传文件保存路径 string savepath = server.mappath("uploadfiles") + "\\"; //提供对客户端上载文件的访问 httpfilecollection uploadfiles = system.web.httpcontext.current.request.files; for (int i = 0; i < uploadfiles.count; i++) { system.web.httppostedfile postedfile = uploadfiles[i]; string filename = postedfile.filename;//完整的路径 filename = system.io.path.getfilename(postedfile.filename); //获取到名称 string fileextension = system.io.path.getextension(filename);//文件的扩展名称 string type = filename.substring(filename.lastindexof(".") + 1); //类型 if (uploadfiles[i].contentlength > 0) uploadfiles[i].saveas(savepath + filename); }
2、使用fileupload 上传:
fileupload 类是从 webcontrol 类中得出的,并且它继承了它的所有元素,fileupload 类具有以下这些只读属性:
- filebytes:返回一组将要上传文件的字节码
- filecontent:返回将要被上传的的文件的流对象
- filename:返回将以上传的文件名称
- hasfile:判断控件是否有文件需要上传
- postedfile:返回一个关于已上传文件的参考。
发布的文件以 httppostedfile 形式的对象进行封装,这个对象可以通过 fileupload 类的 postedfile 属性被存取。httppostedfile 类具有以下常用的属性:
- contentlength:返回已上传的文件的字节大小
- contenttype:返回已上传的文件的 mime 类型
- filename:返回文件全名
- inputstream:返回将要被上传的的文件的流对象
前台:
<form id="form1" runat="server"> <div> <asp:fileupload id="fileupload1" runat="server" /> <br /><br /> <asp:button id="btnsave" runat="server" onclick="btnsave_click" text="save" style="width:85px" /> <br /><br /> <asp:label id="lblmessage" runat="server" /> </div> </form>
后台:
protected void btnsave_click(object sender, eventargs e) { stringbuilder sb = new stringbuilder(); if (fileupload1.hasfile) { try { sb.appendformat(" uploading file: {0}", fileupload1.filename); //saving the file fileupload1.saveas("<c:\\savedirectory>" + fileupload1.filename); //showing the file information sb.appendformat("<br/> save as: {0}", fileupload1.postedfile.filename); sb.appendformat("<br/> file type: {0}", fileupload1.postedfile.contenttype); sb.appendformat("<br/> file length: {0}", fileupload1.postedfile.contentlength); sb.appendformat("<br/> file name: {0}", fileupload1.postedfile.filename); } catch (exception ex) { sb.append("<br/> error <br/>"); sb.appendformat("unable to save file <br/> {0}", ex.message); } } else { lblmessage.text = sb.tostring(); } }
3、配置可上传大文件
web.config配置可上传大文件,asp.net默认情况之下只能上传4mb,另外一点就是,maxrequestlength单位是mb。
<system.web> <httpruntime maxrequestlength="102400" usefullyqualifiedredirecturl="true" minfreethreads="8" minlocalrequestfreethreads="4" apprequestqueuelimit="100" enableversionheader="true"/> </system.web>
到此这篇关于asp.net上传文件并配置可上传大文件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持代码网。
发表评论