文件上传
文件上传本来是个很简单的功能点,因为基于安全和效率方面的考虑在传统的动态页面中,文件的最大长度是受限的,下面来列出几种文件上传的方法
1.新建一个htm静态页面
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="js/jquery.min.js" type="text/javascript"></script> <style type="text/css"> .thumb { height: 75px; border: 1px solid #000; margin: 10px 5px 0 0; } </style> </head> <body> <form method="post" action="Handler.ashx" enctype="multipart/form-data"> 请选择文件:<input type="file" id="file1" name="files[]" multiple="true" /> <input type="submit" value="提交" /> </form> </body> </html>
注意:enctype属性要设置成multipart/form-data,multiple="true"表示
file文件可多选,表单提交给Handler.ashx处理
<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.IO; using System.Runtime.InteropServices; using System.Net; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; HttpFileCollection files = context.Request.Files; for (int i = 0; i < files.Count; i++) { files[i].SaveAs(context.Server.MapPath("files\\" + files[i].FileName)); } context.Response.Write("文件保存成功!"); } public bool IsReusable { get { return false; } } }
这样上传,默认上传文件最大为4M,可以通过修改web.config来修改上传的最大文件值
<?xml version="1.0"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <system.web> <compilation debug="true" targetFramework="4.0"/> <!--修改默认的上传文件最大限制和时间--> <httpRuntime executionTimeout="240" maxRequestLength="20480" /> </system.web> </configuration>
当文件过大时,这种方法就不适用了,在网上找了下,可以采用HTML5,RIA(如serverlight,Flex)
我找到了个开源的serverlight文件上传组件http://slfileupload.codeplex.com/releases挺好用的
大家下载试试看吧
浙公网安备 33010602011771号