ASP.NET 使用Request.Files获取<input type=file/>上传文件

我们知道,对于 ASP.NET 的服务器端控件 FileUpload 来说,可以直接用 FileUpload1.PostedFile 这样的代码来获取上传文件框的文件。


但如果我们没有用 FileUpload,而直接用的 <input type="file" name="pic1" /> 这样的 HTML 控件,ASP.NET 又如何取这些内容呢?


用 Request.Files。


Request.Files.Count 客户端传了多少文件过来。此时不论我们使用的是服务端控件还是 HTML 控件,因为到了客户端都是一样的 <input type="file";另外,即使文件上传框中没有选择文件,都可能会当作上传了无内容的文件(视客户端浏览器)。
Request.Files[i].ContentLength 获取上传文件的大小,以字节为单位。
Request.Files[i].ContentType 获取客户端发送的文件的 MIME 内容类型。
Request.Files[i].FileName
Request.Files[i].InputStream
Request.Files[i].SaveAs(string filename)
上面的 Request.Files[i],也可以是 Request.Files[name]。


在类中使用?


在类中,我们这样用:


System.Web.HttpContext.Current.Request.Files


用request.files实现异文件上传(开放式上传)


一直以为只有file框,只有在使用了runat="server"后才可以实现上传文件的功能。
如:
   <form id="form1" method="post" runat="server">
       <input id="File1" type="file" name="File1"/>
       <input id="Submit1" type="submit" value="submit" />
   </form>


其实,这只是一个误区,在.net中file框也可以不使用runat="server"也可以实现上传文件的功能。如:
   <form id="form1" method="post" enctype="multipart/form-data" action="d.aspx">
       <input id="File1" type="file" name="File1"/>
       <input id="Submit1" type="submit" value="submit" />
   </form>


从代码可以看出区别。如果file框没有加runat="server",则form里一定要加上


enctype="multipart/form-data"这样才可以实现上传文件到服务器。


同时可以看到第一个form中使用了runat="server"。而第二个没有。其实使用了server和没有使用


runat="server"是有区别的.使用了runat="server"的form编译后,action必定是指向本身的网页。而没


有加runat="server"的form可以指向一个网页。这样就可以实现异文件上传------与asp的上传方法相似


,但是代码就简便许多。


异文件上传的处理代码如下:
d.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class d : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Files.Count>0)
        {
            HttpPostedFile f = Request.Files[0];
            f.SaveAs(Server.MapPath("002.jpg"));
        }
    }
}


结论:request.files可以实现文件上传的两种方法。并且文件上传的两种方法,在代码页上是没有什么


区别的,重点是在在设计器上。关闭式(runat=server)方法,file框一定要加上runat=server,form也


是一定要加上runat=server。开放式(submit form)则file框和form都不加runat=server,即写成纯html


代码!!!(所以在form中加入method=post enctype="multipart/form-data")。


使用表单文件域(input type=”file”)时,在PostBack中使用Request.Files获取不到文件。研究了半天,发现在input标签中使用runat=”server”后,是能够正常获取的。但是为了前端的元素ID不被修改,我尽可能不使用runat=”server”。


网上查阅了一下,最终让我找到了原因。用了高级货之后,忘本了呵呵。


要让form能够传递文件的话,必须要在form标签中加入enctype=”multipart/form-data”


<form enctype="multipart/form-data" ID="form1" runat="server">
      <input type="file" name="filename" />
</form>
在input 中使用了runat=”server”,那么ASP.NET会自动处理这些事情,而如果我们要自己DIY,就得记住这些啦!
  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Scott Worley Publisher: New Riders Publishing First Edition November 15, 2001 ISBN: 0-7357-1135-6, 730 pages Inside ASP.NET Here’s what reviewers are saying about Inside ASP.NET: About the Author Contributing Authors About the Technical Reviewers Acknowledgments Tell Us What You Think! Introduction Who Is This Book For? Contents of the Book I: Introducing ASP.NET 1. An Overview of ASP.NET ASP.NET The .NET Base Class Libraries ASP.NET Web Application Configuration Session and State Management Cache Management ASP.NET Web Application Development Layers Web Forms XML Web Services COM/COM+ Interoperability and Component Services ADO.NET Migration from Classic ASP to ASP.NET Globalization and Localization Enhanced Security 2. Developing Applications with ASP.NET Application Settings Files The Page Syntax Commonly Used Objects and Classes in ASP.NET Tracing ASP.NET Applications ASP.NET Migration Issues Summary 3. Configuring ASP.NET Applications Deploying the web.config Configuration File Using the <appSettings> Configuration Section Analyzing the system.web Configuration Sections Summary II: Core ASP.NET 4. Web Form-Based Development Introduction to Web Forms Web Form Architecture Separating Code from the User Interface Server Controls Validation Controls Summary 5. State Management in ASP.NET What Is State Management? Using ASP.NET Application State Management Summary III: ASP.NET and Data Access 6. Using ADO.NET in ASP.NET Applications Data Access from a Web-Based Perspective ADO and ADO.NET Working with the Main ADO.NET Objects Building Data-Oriented Web Forms Transaction-Enabled ASP.NET Applications Summary 7. Using XML in ASP.NET Applications XML Document Structure How XML Is Used in ASP.NET Other XML Technologies Using XML in Your Application Real-World Examples Summary IV: Advanced Technologies 8. XML Web Service Development in ASP.NET Introduction to XML Web Services Using the SOAP Toolkit with XML Web Services XML Web Service Discovery—Advertising Your Service Using an XML Web Service in ASP.NET Pages Summary 9. Securing ASP.NET Applications Overview of ASP.NET Security Features Applying Security in ASP.NET Applications Inside ASP.NET Security Other Security Considerations Summary 10. Using Component Services with ASP.NET What Are Component Services? Applying Component Services in an ASP.NET Application The business Object Using the business Object Serviced Components Summary 11. Using Messaging Services with ASP.NET Introduction to Messaging Systems Managing MSMQ Message Queues with Windows 2000 Architecture of the .NET Messaging Services Accomplishing Tasks Using MSMQ and .NET Summary 12. Using Directory Services with ASP.NET Introducing Directory Services How Does Active Directory Work? The Benefits of Active Directory Active Directory Technology Summary Summary 13. Localizing and Globalizing ASP.NET Applications What Is Localization? Localizing an ASP.NET Web Application Summary V: Advanced Web Forms 14. Cache Control in ASP.NET ASP.NET Cache Management Page Output Caching Fragment Caching (Partial Page Caching) Request Caching Summary 15. Creating User and Custom Controls for ASP.NET User Controls Introduction to Custom Controls Summary 16. Mobile Device Development with ASP.NET Wireless Application Protocol (WAP) Wireless Markup Language (WML) Enter ASP.NET Summary VI: Putting It All Together 17. Putting It All Together What Is ProjectPal? Installing the ProjectPal Application A Brief Application Walkthrough Application Architecture ProjectPal Service Layers ProjectPal Client Interfaces The ProjectPal Database The ProjectPal Components Inside the ProjectPal Code Summary VII: Appendixes A. An Overview of .NET Multiple Development Platforms Multiple Development Languages .NET Base Class Libraries Common Language Runtime (CLR) Common Type System (CTS) .NET Server Products B. ASP.NET Common Object Reference HttpContext Object (Context Intrinsic Control) The HttpApplication Class The HttpApplicationState Class (Application Intrinsic Object) The HttpSessionState Class ( Session Intrinsic Object) The HttpRequest Class (Request Intrinsic Object) The HttpResponse Class (Response Intrinsic Object) The Server Class ( HttpServerUtility ) SMTPMail API C. ADO Common Object Reference DataSet Object DataTable Object DataColumn Object DataRow Class DataRelation Object DataView Object DataRowView Class OLEDBDATA Objects SQLData … Objects D. HTML Server Control Reference HtmlForm Object— < form> Element HtmlInputText Object— < input> Element HtmlInputHidden Object— < input type=“hidden”> Element HtmlInputCheckbox Object— < input type=”checkbox”> Element HtmlInputRadioButton Object— < input type=“radiobutton”> Element HtmlInputFile Object— < input type=“file”> Element HtmlTextArea Object— < textarea> Element HtmlButton Object— < button> Element HtmlInputButton Object— < input type=“button”> Element HtmlAnchor Object— < a> Element HtmlImage Object— < img> Element HtmlInputImage Object— < input type=“image”> Element HtmlSelect Object— < select> and <option> Elements HtmlTable Object— < table> Element HtmlTableRow Object— < tr> Element HtmlTableCell Object— < td> Element E. ASP Server Control Reference Common Properties of the Webcontrol Class The Label Control The Image Control The TextBox Control The DropDownList Control The ListBox Control The CheckBox Control The CheckBoxList Control The RadioButton Control The RadioButtonList Control The Button Control The LinkButton Control The ImageButton Control The HyperLink Control The Table Control The TableCell Control The TableRow Control The Panel Control The Repeater Control The DataList Control The DataGrid Control The AdRotator Control The Calendar Control F. Microsoft Mobile Internet Toolkit Control Groups Form and Layout Controls Presentation Controls Navigation Controls Data Entry Controls Validation Controls G. .NET Resource List ASP.NET Web Hosting Sites ASP.NET Web Sites C# Web Sites Visual Basic .NET Web Sites .NET Web Sites XML Web Services Microsoft .NET Websites Microsoft .NET Newsgroups .NET Mailing Lists Magazines
第1个上传组件commons-fileupload =============commons-fileupload ================ common-fileupload组件是apache的一个开源项目之一,可以从http://jakarta.apache.org/commons/fileupload/下载。该组件简单易用,可实现一次上传一个或多个文件,并可限制文件大小。 -下载后解压zip包,将commons-fileupload-1.1.1.jar,和commons-io-1.2.jar(这里我们用的是更新的版本,但是用法是一样的)复制到tomcat的webapps\你的webapp\WEB-INF\lib\下,如果目录不存在请自建目录。 新建一个servlet: FileUpload.java用于文件上传: package com.drp.util.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.*; import java.util.*; import java.util.regex.*; import java.io.*; import org.apache.commons.fileupload.servlet.*; import org.apache.commons.fileupload.disk.DiskFileItemFactory; public class FileUpload extends HttpServlet { private String uploadPath = ""; // 用于存放上传文件的目录 private File tempPath = new File("D:\\Tomcat 5.5\\webapps\\drp1.2\\tempimages\\"); // 用于存放临时文件的目录 public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html; charset=GB18030"); PrintWriter out = res.getWriter(); System.out.println(req.getContentLength()); System.out.println(req.getContentType()); DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory //允许设置内存中存储数据的门限,单位:字节 factory.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() //如果文件大小大于SizeThreshold,则保存到临时目录 factory.setRepository(new File("D:\\Tomcat 5.5\\webapps\\drp1.2\\tempimages")); ServletFileUpload upload = new ServletFileUpload(factory); // maximum size before a FileUploadException will be thrown //最大上传文件,单位:字节 upload.setSizeMax(1000000); try { List fileItems = upload.parseRequest(req); // assume we know there are two files. The first file is a small //

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值