如何c#中记事本编写语言那些控件代码将fileupload控件上传

穷一年之力,与你相会于北航
文件上传控件Fileupload(实现文件上传并写入数据库)
首先我们来说一下Fileupload这个文件上传控件的几大败笔:
1.上传之后按F5刷新,重复提交
2.提交以后按后退键Fileupload中的信息还在
3.不支持多文件上传
4.上传前不能检测文件大小
解决方法:
1.建立iframe在子页面实现或者重定向语句(Response.Redirect(Request.RawUrl);)
2.用JavaScript语句将fileupload中的val信息清空
4.利用js代码:fileupload.files[0].size代码解决,但需要浏览器支持html5
另外,需要强调的是如果要更改默认上传文件的最大值以及上传时间需要去web.config文件去修改
&httpRuntime maxRequestLength="8192" executionTimeout="90"/&
下面是利用iframe实现文件上传并写入数据库的例程:
iframe.aspx
&%@ Page Language="C#" AutoEventWireup="true" CodeFile="iframe_upload.aspx.cs" Inherits="uploadfiles_iframe_upload" %&
&!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&
&form id="form1" runat="server"&
&h2&upload上传文件保存到数据库&/h2&
&iframe frameborder="0" width="100%" src="i_upload.aspx"&&/iframe&
i_upload.aspx
&%@ Page Language="C#" AutoEventWireup="true" CodeFile="i_upload.aspx.cs" Inherits="uploadfiles_iframe_upload" %&
&!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"&
&script src="../jquery-1.11.3.min.js" type="text/javascript"&&/script&
&title&&/title&
&script type="text/javascript"&
$(document).ready(function () {
$("#fup1").val(""); //将fileupload中的val信息清空
function checkdata() {
if ($("#fup1").val() == "") {
alert("请选择文件");
$("#fup1").focus(); //将焦点定在fileupload控件上
var _file = document.getElementById("fup1"); //寻找页面中特定ID值的控件
var _size = _file.files[0]. //在提交之前提取文件的大小
if (_size & 4000000) {
alert("文件过大");
$("#fup1").focus();
&form id="form1" runat="server"&
&asp:FileUpload ID="fup1" runat="server" /&
&asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" OnClientClick="return checkdata()" /&
i_upload.aspx.cs
using System.Collections.G
using System.L
using System.W
using System.Web.UI;
using System.Web.UI.WebC
public partial class uploadfiles_iframe_upload : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
protected void Button1_Click(object sender, EventArgs e)
Session["_tempFiles"] = fup1.PostedF //将信息写入session
Response.Redirect("i_info.aspx"); //转到i_info页面
i_info.aspx
&%@ Page Language="C#" AutoEventWireup="true" CodeFile="i_info.aspx.cs" Inherits="uploadfiles_iframe_upload" %&
&!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&
&form id="form1" runat="server"&
title:&asp:TextBox ID="TextBox1" runat="server"&&/asp:TextBox&&br /&
fc_id:&asp:Label ID="lb_fcid" runat="server" Text="Label"&&/asp:Label&&br/&
fc_name:&asp:Label ID="lb_fcname" runat="server" Text="Label"&&/asp:Label&&br/&
targDir:&asp:Label ID="lb_tdir" runat="server" Text="Label"&&/asp:Label&&br/&
targPath:&asp:Label ID="lb_fcpath" runat="server" Text="Label"&&/asp:Label&&br /&
&asp:Button ID="Button1" runat="server" Text="保存" onclick="Button1_Click" /&
i_info.aspx.cs
using System.Collections.G
using System.L
using System.W
using System.Web.UI;
using System.Web.UI.WebC
using System.IO;
using System.Data.OleDb;
public partial class uploadfiles_iframe_upload : System.Web.UI.Page
string str_cnn = "Provider=MicroSoft.Jet.OLEDB.4.0;Data Source=";
string str_sourcefile = "~/uploadfiles/data.mdb";
OleDbDataR
string str_
protected void Page_Load(object sender, EventArgs e)
if (Session["_tempFiles"] == null)
Response.Redirect("i_upload.aspx");
HttpPostedFile _myfiles = (HttpPostedFile)Session["_tempFiles"]; //读取session,存入_myfiles中
string _ext = Path.GetExtension(_myfiles.FileName).ToLower(); //获取文件的扩展名,并转化为小写
string str_conn = str_cnn + MapPath(str_sourcefile);
cnn = new OleDbConnection(str_conn);
cnn.Open();
//设置默认值
lb_fcid.Text = "1";
lb_fcname.Text = "其他";
lb_tdir.Text = "~/uploadfiles/其他";
str_sql = "SELECT * FROM T_FILE WHERE fc_ext like '%" + _ext + "%'";//注意变量值的分离方法
cmd = new OleDbCommand(str_sql, cnn);
deter = cmd.ExecuteReader();
&span style="white-space:pre"& &/span&//读数据库
while (deter.Read())
lb_fcid.Text = deter["ID"].ToString();
lb_fcname.Text = deter["fc_name"].ToString();
lb_tdir.Text = deter["fc_path"].ToString();
TextBox1.Text = _myfiles.FileName.ToString();
lb_fcpath.Text = MapPath(lb_tdir.Text) + DateTime.Now.ToOADate() + _ //构建文件路径
cnn.Close();
protected void Button1_Click(object sender, EventArgs e)
string _targPath = lb_fcpath.T
string _targDir = lb_tdir.T
Directory.CreateDirectory(MapPath(_targDir)); //检查有无文件目录,如果没有则创建
((HttpPostedFile)Session["_tempfiles"]).SaveAs(_targPath);//存文件
if (File.Exists(_targPath))
string _fname, _fcid, _
_fname = Path.GetFileName(lb_fcpath.Text);
_fcid = lb_fcid.T
_title = TextBox1.T
string str_conn = str_cnn + MapPath(str_sourcefile);
cnn = new OleDbConnection(str_conn);
cnn.Open();
&span style="white-space:pre"& &/span&//存入数据库
str_sql = "INSERT INTO T_FILEINFO(f_name,f_path) values "+"('"+_fname+"','"+_title+"')";
cmd = new OleDbCommand(str_sql, cnn);
int i = cmd.ExecuteNonQuery();
cnn.Close();
if (i & 0)
Session.Remove("_tempfiles");//清除session
Response.Redirect("i_down.aspx");
i_down.aspx
&%@ Page Language="C#" AutoEventWireup="true" CodeFile="i_down.aspx.cs" Inherits="uploadfiles_iframe_upload" %&
&!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&
&form id="form1" runat="server"&
&p&上传成功&/p&
&asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/uploadfiles/i_upload.aspx"&再次上传&/asp:HyperLink&
FileUpload 上传文件 详细参数设置
前后台代码
.net C# FileUpload控件上传
[.Net码农]将文件上传到数据库 和 从数据库下载文件到本地
html文件上传控件file自定义样式
几款极好的 JavaScript 文件上传插件
20款最好的jQuery文件上传插件
十个非常好用的文件上传工具(插件)
type为file的input控件文件上传打开缓慢
没有更多推荐了,用fileupload组件实现的大文件上传简单实例
转载 &更新时间:日 11:37:37 & 投稿:jingxian
下面小编就为大家带来一篇用fileupload组件实现的大文件上传简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
1.FileUploadServlet.java文件,实现上传处理
import java.io.F
import java.io.IOE
import java.io.PrintW
import java.text.DecimalF
import java.util.I
import java.util.L
import javax.servlet.ServletE
import javax.servlet.http.HttpS
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import org.apache.commons.fileupload.FileI
import org.apache.commons.fileupload.FileUploadE
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededE
import org.apache.commons.fileupload.disk.DiskFileItemF
import org.apache.commons.fileupload.servlet.ServletFileU
public class FileUploadServlet extends HttpServlet
private static final long serialVersionUID = 1L;
public FileUploadServlet()
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
this.doPost(request, response);
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
final long MAX_SIZE = 2048 * 1024 * 1024;// 设置上传文件最大值为2G,可以改为更大
// 允许上传的文件格式的列表
final String[] allowedExt = new String[]
{ "exe","jpg","DT" };
response.setContentType("text/html");
// 设置字符编码为UTF-8, 统一编码,处理出现乱码问题
response.setCharacterEncoding("UTF-8");
// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
// 用以上工厂实例化上传组件
ServletFileUpload sfu = new ServletFileUpload(dfif);
// 设置最大上传大小
sfu.setSizeMax(MAX_SIZE);
PrintWriter out = response.getWriter();
// 从request得到所有上传域的列表
List fileList =
fileList = sfu.parseRequest(request);
} catch (FileUploadException e)
{// 处理文件尺寸过大异常
if (e instanceof SizeLimitExceededException)
out.println("文件尺寸超过规定大小:" + MAX_SIZE + "字节&p /&");
out.println("&a href=\"FileUpload.html\" target=\"_top\"&返回&/a&");
e.printStackTrace();
// 没有文件上传
if (fileList == null || fileList.size() == 0)
out.println("请选择上传文件&p /&");
out.println("&a href=\"FileUpload.html\" target=\"_top\"&返回&/a&");
//文件大小取两位小数
DecimalFormat digit=new DecimalFormat("0.00");
// 得到所有上传的文件
Iterator fileItr = fileList.iterator();
// 循环处理所有文件
while (fileItr.hasNext())
FileItem fileItem =
String path =
double size = 0;
// 得到当前文件
fileItem = (FileItem) fileItr.next();
// 忽略简单form字段而不是上传域的文件域(&input type="text" /&等)
if (fileItem == null || fileItem.isFormField())
// 得到文件的大小,K为单位并保留两位小数
size = (double)fileItem.getSize()/1024;
if ("".equals(path) || size == 0)
out.println("&html&&head&&title&上传处理界面&/title&&/head&");
out.println("请选择上传文件&p /&");
out.println("&a href=\"FileUpload.html\" target=\"_top\"&返回&/a&");
out.println("&/html&");
// 得到文件的完整路径
path = fileItem.getName();
// 得到去除路径的文件名
String t_name = path.substring(path.lastIndexOf("\\") + 1);
// 得到文件的扩展名(无扩展名时将得到全名)
String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
// 拒绝接受规定文件格式之外的文件类型
int allowFlag = 0;
int allowedExtCount = allowedExt.
for (; allowFlag & allowedExtC allowFlag++)
if (allowedExt[allowFlag].equals(t_ext))
if (allowFlag == allowedExtCount)
out.println("&html&&head&&title&上传处理界面&/title&&/head&");
out.println("请上传以下类型的文件&p /&");
for (allowFlag = 0; allowFlag & allowedExtC allowFlag++)
out.println("*." + allowedExt[allowFlag]
out.println("&p /&&a href=\"FileUpload.html\" target=\"_top\"&返回&/a&");
out.println("&/html&");
// 保存文件到服务器根目录下
fileItem.write(new File("\\"+t_name));
System.out.println(t_name);
out.println("&html&&head&&title&上传处理界面&/title&&/head&");
out.println("文件名称为:" + path + "&br&");
out.println("文件上传成功, 已保存为: " + t_name
+ "&br&"+" 文件大小: " + digit.format(size) + "K &p /&");
out.println("&a href=\"FileUpload.html\" target=\"_top\"&继续上传&/a&");
out.println("&/html&");
} catch (Exception e)
e.printStackTrace();
&2.FileUpload.html文件,实现上传页面。
&meta http-equiv="Content-Type" content="text/ charset=UTF-8"&
&title&文件上传&/title&
&form action="FileUploadServlet" method="post"
enctype="multipart/form-data"&
&input type="file" size="30"
name="file01" /&&br&
&pre& &input name="submit" type="submit" value="上传"& &input name="reset" type="reset" value="重置"&
3.配置web.xml文件中的的servlet和过滤器,过滤器解决上传文件名为中文时出现乱码。
&?xml version="1.0" encoding="UTF-8"?&
&web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&
&display-name&FileUploadServlet&/display-name&
&servlet-name&FileUploadServlet&/servlet-name&
&servlet-class&FileUploadServlet&/servlet-class&
&/servlet&
&servlet-mapping&
&servlet-name&FileUploadServlet&/servlet-name&
&url-pattern&/FileUploadServlet&/url-pattern&
&/servlet-mapping&
&filter-name&setCharacterEncoding &/filter-name&
&filter-class&com.xulu.EncodingChange&/filter-class&
&init-param&
&param-name&ignore &/param-name&
&param-value&true &/param-value&
&/init-param&
&init-param&
&param-name&encoding &/param-name&
&param-value&UTF-8 &/param-value&
&/init-param&
&filter-mapping&
&filter-name&setCharacterEncoding &/filter-name&
&url-pattern&/* &/url-pattern&
&/filter-mapping&
&welcome-file-list&
&welcome-file&index.jsp&/welcome-file&
&/welcome-file-list&
&login-config&
&auth-method&BASIC&/auth-method&
&/login-config&
&/web-app&
4.过滤器文件EncodingChange.java和setCharacterEncoding.java分别如下,并且在根目录下的WEB-INF\classes\com\xulu文件夹中放入他它们编译生成的.class文件
package com.
import java.io.IOE
import javax.servlet.*;
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
public class EncodingChange implements Filter
protected String encoding =
protected FilterConfig filterconfig =
protected boolean ignore =
public void destroy()
this.encoding =
this.filterconfig =
public void doFilter(ServletRequest requests, ServletResponse responses,
FilterChain chain) throws IOException, ServletException
// TODO Auto-generated method stub
HttpServletRequest request = (HttpServletRequest)
HttpServletResponse response = (HttpServletResponse)
if (ignore || request.getCharacterEncoding() == null)
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
request.getSession().getAttribute("Login_Student");
request.getSession().getAttribute("Login_Teacher");
request.getSession().getAttribute("Login_Admin");
chain.doFilter(request, response);
public void init(FilterConfig filterconfig) throws ServletException
// TODO Auto-generated method stub
this.filterconfig =
this.encoding = filterconfig.getInitParameter("encoding");
String value = filterconfig.getInitParameter("ignore");
if (value == null)
this.ignore =
} else if (value.equalsIgnoreCase("true"))
this.ignore =
} else if (value.equalsIgnoreCase("yes"))
this.ignore =
this.ignore =
public String selectEncoding(ServletRequest request)
return this.
package com.
import java.io.IOE
import javax.servlet.*;
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
public class setCharacterEncoding implements Filter{
protected String encoding=
protected FilterConfig filterconfig=
protected boolean ignore=
public void destroy() {
this.encoding=
this.filterconfig=
public void doFilter(ServletRequest requests, ServletResponse responses,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request=(HttpServletRequest)
HttpServletResponse response=(HttpServletResponse)
if(ignore||request.getCharacterEncoding()==null){
String encoding=selectEncoding(request);
if(encoding!=null){
request.setCharacterEncoding(encoding);
request.getSession().getAttribute("Login_Student");
request.getSession().getAttribute("Login_Teacher");
request.getSession().getAttribute("Login_Admin");
chain.doFilter(request, response);
public void init(FilterConfig filterconfig) throws ServletException {
// TODO Auto-generated method stub
this.filterconfig =
this.encoding = filterconfig.getInitParameter("encoding");
String value = filterconfig.getInitParameter("ignore");
if (value == null) {
this.ignore =
} else if (value.equalsIgnoreCase("true")) {
this.ignore =
} else if (value.equalsIgnoreCase("yes")) {
this.ignore =
this.ignore =
public String selectEncoding(ServletRequest request){
return this.
5.在浏览器中就可以实现页面的上传了,访问http://localhost:8080/**/FileUpload.html就可以了。其中**为自己命名的web文件夹,如DoUpload,上面的文件都在该目录里,且DoUpload文件夹放在Tomcat的webapp文件夹下。
补充:在上述所有步骤之前需引入三个.jar文件,分别为commons-fileupload-1.2.1.jar,commons-io-1.4.jar和servlet-api.jar网上可以下载到
以上就是小编为大家带来的用fileupload组件实现的大文件上传简单实例的全部内容了,希望对大家有所帮助,多多支持脚本之家~
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具ASP.NET中FileUpload中的代码怎么编写?_百度知道
ASP.NET中FileUpload中的代码怎么编写?
点击浏览后有个上传按钮,上传到我建的FileUploda文件夹下,这个FileUploda控件里面的代码要怎么实现?
答题抽奖
首次认真答题后
即可获得3次抽奖机会,100%中奖。
protected void submit_Click(object sender, EventArgs e)
string name = FileUpload1.FileN
int size = FileUpload1.PostedFile.ContentL
string type = FileUpload1.PostedFile.ContentT
//image/pjpeg
// string type2 = name.Substring(name.LastIndexOf(&.&) + 1);
//jpg 不安全
string ipath = Server.MapPath(@&~\img\&) +
string dpath = @&~\img\& +
if (type.Contains(&image&))
if (size & 1048576)
FileUpload1.SaveAs(ipath);
Image1.Visible =
Image1.ImageUrl =
Response.Write(&恭喜你上传成功!&);
Response.Write(&图片过大!请上传小于1MB的图片&);
Response.Write(&请上传正确的图片格式&);
采纳率:16%
&asp:FileUpload ID=&fuPhoto& onchange=&javascript:__doPostBack('lbUploadPhoto','')&
runat=&server& ToolTip=&选择图片& /&&asp:LinkButton ID=&lbUploadPhoto& runat=&server& OnClick=&lbUploadPhoto_Click&&&/asp:LinkButton&后台代码:
//自动上传事件
protected void lbUploadPhoto_Click(object sender, EventArgs e)
fileUpload();
//从控件上传文件
public void fileUpload()
if (fuPhoto.PostedFile != null && fuPhoto.PostedFile.ContentLength & 0)
string ext = System.IO.Path.GetExtension(fuPhoto.PostedFile.FileName).ToLower();
if (ext != &.jpg& && ext != &.jepg& && ext != &.bmp& && ext != &.gif&)
string filename = &Image_& + DateTime.Now.ToString(&yyyyMMddHHmmss&) +
string path = &./UploadPhoto/& +
fuPhoto.PostedFile.SaveAs(Server.MapPath(path));
Response.Redirect(&ImageCut.aspx?Picurl=& + Server.UrlEncode(path));
这是上传图片的,你可以改成自己想要的格式,也看添加别的格式 string imgname = this.File1.PostedFile.FileName.Substring(this.File1.PostedFile.FileName.LastIndexOf('\\') + 1);
string Extension = System.IO.Path.GetExtension(imgname).ToLower();
if (Extension == &.gif& || Extension == &.jpg&)
if (File1.PostedFile.ContentLength & 1024000)
Page.ClientScript.RegisterStartupScript(this.GetType(), &&, &&script&alert('上传图片的大小不能超过1M!')&/script&&);
string newname = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + E
System.Drawing.Image img = System.Drawing.Image.FromStream(File1.PostedFile.InputStream);
img.Save(Server.MapPath(&~/uploads/& + newname), System.Drawing.Imaging.ImageFormat.Jpeg);
this.upimage.Text =
Page.ClientScript.RegisterStartupScript(this.GetType(), &&, &&script&alert('上传图片格式错误')&/script&&);
if (UpLoadFile1.PostedFile != null)
string strFile = UpLoadFile1.PostedFile.FileN
//string fex = Path.GetExtension(UpLoadFile1.PostedFile.FileName);
if (strFile.Substring(strFile.LastIndexOf('.') + 1).ToLower() != &jpg& && strFile.Substring(strFile.LastIndexOf('.') + 1).ToLower() != &jpeg& && strFile.Substring(strFile.LastIndexOf('.') + 1).ToLower() != &gif& && strFile.Substring(strFile.LastIndexOf('.') + 1).ToLower() != &bmp&)
Label4.Text = &只能上传 jpg,jpeg,gif,和bmp 格式的照片!&;
Random ro = new Random();
string stro = ro.Next(100, ).ToString() ;//产生一个随机数用于新命名的图片
string NewName = DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString()+
string kz = strFile.Substring(strFile.LastIndexOf('.'));
string fileSavePath = Server.MapPath(&./flash/&) + NewName+
UpLoadFile1.PostedFile.SaveAs(fileSavePath);
string url = &admin/flash/& + NewName+
string name = Server.HtmlEncode(TextBox1.Text.Trim());
string content = Server.HtmlEncode(TxtContent.Text.Trim().Replace(&'&, &&));
DateTime dtt = DateTime.N
int id = Convert.ToInt32(DropDownList2.SelectedValue);
sc.ExecSql(&insert into [ilev3]([name],[content],[photo],[dtt],[ilev2id])values('& + name + &','& + content + &','& + url + &','& + dtt + &',& + id + &)&);
Response.Write(&&script language='javascript'&alert('添加信息成功!');&/script&&);
Response.Write(&&script &alert('上传照片出错!请重试!');&/script&&);
其他1条回答
为您推荐:
其他类似问题
fileupload的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。fileUpload 控件怎样用js获得上传文_百度知道
fileUpload 控件怎样用js获得上传文
答题抽奖
首次认真答题后
即可获得3次抽奖机会,100%中奖。
示例代码:&form action=&& method=&get& onSubmit=&&&
&input type=&text& name=&test& id=&test&&
&input type=&file& name=&testFile& onChange=&if(this.value)insertTitle(this.value);&&&input type=&submit& value=&提交&&
&script language=&javascript&&
function insertTitle(path){
var test1 = path.lastIndexOf(&/&);
采纳率:90%
为您推荐:
其他类似问题
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。

我要回帖

更多关于 c# 编写step步骤控件 的文章

 

随机推荐