在研究HttpRequest的时候,搞文件上传的时候,经常碰到返回HttpPostedFile对象的情况,这个对象才是真正包含文件内容的东西。
经常要获取的最重要的内容是FileName属性与SavaAs方法,现在我们来详细看看这个东西。
一、常用属性
- ContentLength: 获取上载文件的大小(以字节为单位)。返回一个数字。
- ContentType:获取客户端发送的文件的 MIME 内容类型。
- FileName: 获取客户端上的文件的完全限定名称。
- InputStream:获取一个 Stream 对象,该对象指向一个上载文件,以准备读取该文件的内容。
二、常用方法
- SaveAs 保存上载文件的内容。 可以服务器物理路径作为参数。
代码示例:
注意表单要加上enctype = "multipart/form-data",后台FileCollect.Count才不会为0。如:
<form action="/Home/GetForm" method="post" enctype="multipart/form-data"> <p><input type="file" name="file1" value="" /></p> <p><input type="file" name="file2" value="" /></p> <p><input type="submit" value="提交" /></p> </form> public ActionResult GetForm() { HttpRequest request = System.Web.HttpContext.Current.Request; HttpFileCollection FileCollect = request.Files; if (FileCollect.Count > 0) //如果集合的数量大于0 { foreach (string str in FileCollect) { HttpPostedFile FileSave = FileCollect[str]; //用key获取单个文件对象HttpPostedFile string imgName = DateTime.Now.ToString("yyyyMMddhhmmss"); string imgPath = "/" + imgName + FileSave.FileName; //通过此对象获取文件名 string AbsolutePath = Server.MapPath(imgPath); FileSave.SaveAs(AbsolutePath); //将上传的东西保存 Response.Write("<img src='" + imgPath + "'/>"); } } return Content("键值对数目:" + FileCollect.Count); }HttpPostedFile 多文件上传实例
<form id="form1" runat="server"> <div> <table style="width: 343px"> <tr> <td style="width: 100px"> 多文件上传</td> <td style="width: 100px"> </td> </tr> <tr> <td style="width: 100px"> <asp:FileUpload ID="FileUpload1" runat="server" Width="475px" /> </td> <td style="width: 100px"> </td> </tr> <tr> <td style="width: 100px"> <asp:FileUpload ID="FileUpload2" runat="server" Width="475px" /></td> <td style="width: 100px"> </td> </tr> <tr> <td style="width: 100px"> <asp:FileUpload ID="FileUpload3" runat="server" Width="475px" /></td> <td style="width: 100px"> </td> </tr> <tr> <td style="width: 100px"> <asp:Button ID="bt_upload" runat="server" OnClick="bt_upload_Click" Text="一起上传" /> <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="448px"></asp:Label></td> <td style="width: 100px"> </td> </tr> </table> </div> </form>protected void bt_upload_Click(object sender, EventArgs e) { if (FileUpload1.PostedFile.FileName == "" && FileUpload2.PostedFile.FileName == "" && FileUpload3.PostedFile.FileName == "") { this.lb_info.Text = "请选择文件!"; } else { HttpFileCollection myfiles = Request.Files; for (int i = 0; i < myfiles.Count; i++) { HttpPostedFile mypost = myfiles[i]; try { if (mypost.ContentLength > 0) { string filepath = mypost.FileName;//C:/Documents and Settings/Administrator/My Documents/My Pictures/20022775_m.jpg string filename = filepath.Substring(filepath.LastIndexOf("//") + 1);//20022775_m.jpg string serverpath = Server.MapPath("~/images/") + filename;//C:/Inetpub/wwwroot/WebSite2/images/20022775_m.jpg mypost.SaveAs(serverpath); this.lb_info.Text = "上传成功!"; } } catch (Exception ex) { this.lb_info.Text = "上传发生错误!原因:" + ex.Message.ToString(); } } } }