文件上传控件asp:FileUpload

前端

使用的控件<asp:FileUpload ID="fileup" runat="server" /><span class="message">*</span>

$("#btn_Save_").click(function () {
var url = "Upload.aspx?_method=import";
// url += "&_method=import";
form1.action = url;
form1.submit();
});

后端:

准备 操作Excel,csv等等的通用类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.IO;

namespace Holworth.Utility
{
public class ExcelUtil
{
public static DataTable GetCSV(string path)
{
DataTable dt = new DataTable();
bool isDtHasColumn = false; //标记DataTable 是否已经生成了列 
StreamReader reader = new StreamReader(path, System.Text.Encoding.Default); //数据流 
while (!reader.EndOfStream)
{
string message = reader.ReadLine();
string[] splitResult = message.Split(new char[] { ‘,‘ },StringSplitOptions.None); //读取一行 以逗号分隔 存入数组 
if (splitResult.Length <= 1)
{
continue;
}
DataRow row = dt.NewRow(); 
if (!isDtHasColumn)
{
for (int i = 0; i < splitResult.Length; i++)
{
if (!isDtHasColumn) //如果还没有生成列 
{
dt.Columns.Add("column" + i, typeof(string));
}
}
isDtHasColumn = true;
continue;
}
isDtHasColumn = true;
row = dt.NewRow();
for (int i = 0; i < splitResult.Length&&i<dt.Columns.Count; i++)
{
row[i] = splitResult[i].Trim().Replace("\"", "");
}
dt.Rows.Add(row); //添加行 
}
return dt;
}
public static DataTable GetExcelSheetContent(string strPath, string sheetName)
{
string mystring = "";
DataTable dt = new DataTable();
mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = ‘" + strPath + "‘;Extended Properties=‘Excel 8.0;HDR=NO;IMEX=1;‘";
if (System.IO.Path.GetExtension(strPath).ToLower().EndsWith("xlsx"))
{
mystring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties=‘Excel 12.0;HDR=YES‘";
}
OleDbConnection connection = new OleDbConnection(mystring);
OleDbDataAdapter da = null;
try
{

da = new OleDbDataAdapter("select * from [" + sheetName + "]", connection);
da.Fill(dt);
return dt;
}
catch (OleDbException err)
{
throw new Exception("执行查询语句时出错:" + err.Message);
}
finally
{
connection.Close();
da.Dispose();
}
}
public static string[] GetExcelTableName(string strPath)
{

string mystring = "";
mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = ‘" + strPath + "‘;Extended Properties=‘Excel 8.0;HDR=YES;IMEX=1;‘";
if (System.IO.Path.GetExtension(strPath).ToLower().EndsWith("xlsx"))
{
mystring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties=‘Excel 12.0;HDR=YES‘";
}
//IList<string> tblNames = null;
DataTable tblSchema = null;
string tableName = "";
OleDbConnection connection = new OleDbConnection(mystring);
try
{
if (connection.State != ConnectionState.Open)
connection.Open();
//Prepare the command
tblSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

string[] mySheetName = new string[tblSchema.Rows.Count];
int i = 0;
foreach (DataRow row in tblSchema.Rows)
{
tableName = row["TABLE_NAME"].ToString();
//tableName = tableName.Replace("‘", "");
//tableName = tableName.Replace("$", "");
//tableName = tableName.Replace("#", ".");
mySheetName[i] = tableName;
i++;
}
return mySheetName;
}
catch (OleDbException err)
{
if (err.ErrorCode == -2147467259)
throw new Exception("您选择的Excel文件不是预期的格式!");
else
throw new Exception("执行查询语句时出错:" + err.Message);
}
finally
{
connection.Close();
}
return null;
}
}
}

//前面为准备类ExcelUtil用户读取excel,csvd等

protected void Page_Load(object sender, EventArgs e)
{
if (Request["_method"] == "import")
{
Import();
}
}
private void Import()
{
string fileName = Server.MapPath("~/upload/" + DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xlsx");

//把文件保存到指定的路径

this.fileup.SaveAs(fileName);
if (string.IsNullOrEmpty(fileup.FileName))
{
ScriptHelper.MessageBox(false, "请选择文件不能上传空文件",0);
return;
}
//Psvc.SaveInsertMktRateMarketData(fileName, Request["drp_DataType_"] == "1", false);
GetExcelDirectory(fileName);
System.IO.File.Delete(fileName);
SaveLog(string.Empty, "导入");

//读取43张ExcelSheet 进行验证 并把数据导入到(数据库)

ScriptHelper.MessageBox(true, "Import_Sucess", 1);

}

DataTable dtMulu = new DataTable();
public void GetExcelDirectory(string fileName)
{
beginProgress();
// System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();
;
//if (fd.ShowDialog() == DialogResult.OK)
{
//读取某路径下fileName下的某个ExcelSheet的内容,所有行读出来放到DataTable 里
dtMulu = ExcelUtil.GetExcelSheetContent(fileName, "目录$");

//获取某Excel文件下的所有DataTable的表名放到一个字符串数组中
string[] dtAllTable = ExcelUtil.GetExcelTableName(fileName);
HraWeb.ReportEg.To38Validate.Validate.FX_FORWARD_V fc = new HraWeb.ReportEg.To38Validate.Validate.FX_FORWARD_V();
int len = dtAllTable.Length;
int i = 1;
double percent = 0.00f;
Framework.QueryInfo infoDle=new Framework.QueryInfo();
infoDle.QueryObject = "To38ImportResult";
IList list = Dao.FindList(infoDle);
List<To38ImportResult> list2 =new List<To38ImportResult>();
foreach (var t in list)
{
list2.Add(t as To38ImportResult);

}
list2.ForEach(a=>a.State.MarkDeleted());
Dao.SaveOrUpdateAll(list2);

foreach (string item in dtAllTable)
{

if (!(item.LastIndexOf("属性表") > 0))
{

#region 反射获取验证页面所在的程序集

Assembly asm = Assembly.GetAssembly(fc.GetType());

#endregion

if (item != "目录$")
{
if (dtAllTable.Length > 0 && dtAllTable != null)
{
string b;
b = item.Replace("$", "");
string tableEn = GetTableToEn(b);

//Type t = asm.GetType("HraWeb.ReportEg.To38Validate.Validate.FX_FORWARD_V");
Type t = asm.GetType(fc.GetType().Namespace + "." + tableEn.Trim() + "_V");//到时候替换成右边这个
object o = Activator.CreateInstance(t);
MethodInfo getSqlMethodInfo = t.GetMethod("TestImport");

if (!string.IsNullOrEmpty(tableEn))
{
getSqlMethodInfo.Invoke(o, new object[] { fileName, item, b});//tableEn

}

}
}

}
if (i == len)
{
percent = 1;
setProgress((percent * 100).ToString().Split(‘.‘)[0]);
finishProgress();
break;

}
percent = i*1.0 / len ;

setProgress((percent * 100).ToString().Split(‘.‘)[0]);
System.Threading.Thread.Sleep(70);
i++;
}
}
}

/* Copyright (c) 2015 Xiamen HaiHui Software Co., Ltd. All rights reserved
* 其中某个验证类
* Create by [email protected] at 2015-01-15 20:25:38
*
*/

using System;
using System.Text;
using System.Web.ApplicationServices;
using Aspose.Cells;
using Contract.Domain;
using Holworth.Utility;
using HraWeb.Common;
using HraWeb.ReportEg.To38Validate.ValidateGenericInterface;
using HraWeb.ReportEg.To38Validate.ValidateInteface;

namespace HraWeb.ReportEg.To38Validate.Validate
{

///<summary>
///外汇远期属性表
///</summary>

public class FX_FORWARD_OPT_V : BasePage,IGenericValidate
{

public void TestImport(string ExcelFileName, string ExcelTabFileNameEN,string ExcelTabFileNameCN)
{
int RecordCount = 0;
To38ImportResult r=new To38ImportResult();
r.Tname = this.GetType().Name.Substring(0, this.GetType().Name.Length - 2); //"FX_FORWARD_OPT_V";
r.TStartTime = DateTime.Now;
//string[] tableName = Holworth.Utility.ExcelUtil.GetExcelTableName(ExcelFileName); //@"c:\1.xls"
//System.Data.DataTable table = Holworth.Utility.ExcelUtil.GetExcelSheetContent(ExcelFileName, ExcelTabFileNameEN); //tableName[0]
System.Data.DataTable table = ExcelUtil.GetExcelSheetContent(ExcelFileName, ExcelTabFileNameEN);
System.Text.StringBuilder etrorSb = new StringBuilder();
int i = 0;
System.Collections.ArrayList list = new System.Collections.ArrayList();
foreach (System.Data.DataRow row in table.Rows)
{
bool v_bool = true;
Contract.Domain.FxForwardOpt a = new Contract.Domain.FxForwardOpt();
string trade_id = row[0].ToString();
//product_id,
string notional_1 = row[1].ToString();
string notional_2 = row[2].ToString();
string trade_date = row[3].ToString();
// string value_date = row[4].ToString();
string optional_date = row[4].ToString();
string maturity_date = row[5].ToString();
string currency_1 = row[6].ToString();
string currency_2 = row[7].ToString();
string counterparty = row[8].ToString();
string folder = row[9].ToString();
string trader = row[10].ToString();
//block_number

if (string.IsNullOrEmpty(row[0].ToString()))//记录结束
{

break;
}
RecordCount++;
if (ValidateCommon.ValidateNotNull(trade_id.ToString()))//验证自己调用
{
a.TradeId = trade_id;
}
else
{
v_bool = false;
etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 1, trade_id));
continue;

}

if (ValidateCommon.ValidatePrice(notional_1))//验证自己调用
{
a.Notional1 = Convert.ToDecimal(notional_1);
}
else
{
v_bool = false;
etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 2, notional_1));
continue;

}
if (ValidateCommon.ValidatePrice(notional_2))//验证自己调用
{
a.Notional2 = Convert.ToDecimal(notional_2);
}
else
{
v_bool = false;
etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 3, notional_2));
continue;

}
if (ValidateCommon.ValidateDateTime(trade_date))//验证自己调用
{
trade_date = ValidateCommon.ValidateDateTimeString(trade_date);
a.TradeDate = Convert.ToDateTime(trade_date);
}
else
{
v_bool = false;
etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 4, trade_date));
continue;

}
if (ValidateCommon.ValidateDateTime(optional_date))//验证自己调用
{
optional_date = ValidateCommon.ValidateDateTimeString(optional_date);
a.OptionalDate = Convert.ToDateTime(optional_date);
}
else
{
v_bool = false;
etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 5, optional_date));
continue;

}

if (ValidateCommon.ValidateDateTime(maturity_date))//验证自己调用
{
maturity_date = ValidateCommon.ValidateDateTimeString(maturity_date);
a.MaturityDate = Convert.ToDateTime(maturity_date);
}
else
{
v_bool = false;
etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 6, maturity_date));
continue;

}

if (ValidateCommon.ValidateCurreny(currency_1))//验证自己调用
{
a.Currency1 = currency_1;
}
else
{
v_bool = false;
etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 7, currency_1));
continue;

}
if (ValidateCommon.ValidateCurreny(currency_2 ))//验证自己调用
{
a.Currency2 = currency_2;
}
else
{
v_bool = false;
etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 8, currency_2));
continue;

}
if (ValidateCommon.ValidateNotNull(counterparty))//验证自己调用
{
a.Counterparty =(counterparty);
}
else
{
v_bool = false;
etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 9, counterparty));
continue;

}
if (ValidateCommon.ValidateNotNull(folder ))//验证自己调用
{

a.Folder = folder;
}
else
{
v_bool = false;
etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 10, folder));
continue;

}
if (ValidateCommon.ValidateNotNull(trader))//验证自己调用
{

a.Trader = (trader);
}
else
{
v_bool = false;
etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 11, trader));
continue;

}
if (a.ValueDate != null)
{
if (a.MaturityDate < a.ValueDate)
{
v_bool = false;
etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行Maturity Date小于Value Date不符合业务规则/r/n", i+2, i + 1));
continue;
}
}
//验证成功后
if(v_bool)
list.Add(a);
a.State.MarkNew();
i++;
}

if (list.Count > 0)
{
Dao.SaveOrUpdateAll(list);
}
r.TEndTime = DateTime.Now;
r.SucRec = list.Count;
r.FaiRec = RecordCount - list.Count;
if (string.IsNullOrEmpty(etrorSb.ToString()))
{
r.Result = "导入完成";

}
else
{
r.Result = etrorSb.ToString();
}

Dao.SaveOrUpdate(r);
if (!string.IsNullOrEmpty(etrorSb.ToString()))
{
SaveLog(string.Empty,"ImportExcel",etrorSb.ToString());
}

}
}

}

时间: 2024-10-17 02:35:26

文件上传控件asp:FileUpload的相关文章

Web大文件上传控件-asp.net-bug修复-Xproer.HttpUploader6.2

版权所有 2009-2016荆门泽优软件有限公司 保留所有权利 官方网站:http://www.ncmem.com/ 产品首页:http://www.ncmem.com/webapp/up6.2/index.asp 在线演示:http://www.ncmem.com/products/up6.2/index.htm 产品介绍:http://www.cnblogs.com/xproer/archive/2012/10/26/2741264.html 升级日志:http://www.cnblogs.

ASP.NET使用文件上传控件上传图片

ASPX代码 <%@ 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/xht

改变FileUpload文件上传控件的显示方式,确认后上传

一.Aspx页面: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUploadDemo.aspx.cs" Inherits="WebApplication1.FileUploadDemo" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN&qu

.Net 使用文件上传控件FileUpload上传图片

例1: 来源:http://long546324.iteye.com/blog/349946 Default.aspx文档: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1

文件上传控件FileUpload用法初步

1 <asp:FileUpload ID="fudTest" runat="server" /> 2 <asp:Button ID="btnUpload" runat="server" Text="上传" OnClick="btnUpload_Click" /> 3 <br /> 4 <asp:Label ID="lblMessage&

因用了NeatUpload大文件上传控件而导致Nonfile portion &gt; 4194304 bytes错误的解决方法

今天遇到一个问题,就是"NeatUpload大文件上传控件而导致Nonfile portion > 4194304 bytes错误",百度后发现了一个解决方法,跟大家分享下: NeatUpload是一个开源的大文件上传控件,非常的强大,支持文件类型过滤.上传进度条显示.多文件上传等强大的功能. 但部署至项目后,有些地方用普通的FileUpload上传时却发生了一个错误(Nonfile portion > 4194304 bytes,文件大于默认值4M),因如果用NeatUp

ExtJS 中文件上传控件

1 Ext.onReady(function(){ 2 var fileUpload = new Ext.FormPanel({ 3 id:'fileUpload', 4 frame:true, 5 fileUpload:true, 6 items:[{ 7 xtype:'textfield', 8 labelStyle : 'text-align:right;', 9 allowBlank:false, 10 fieldLabel:'选择文件', 11 inputType:'file', 12

文件上传控件-如何上传文件-大文件下载

需求:项目要支持大文件上传功能,经过讨论,初步将文件上传大小控制在500M内,因此自己需要在项目中进行文件上传部分的调整和配置,自己将大小都以501M来进行限制. 第一步: 前端修改 由于项目使用的是BJUI前端框架,并没有使用框架本身的文件上传控件,而使用的基于jQuery的Uploadify文件上传组件,在项目使用的jslib项目中找到了BJUI框架集成jQuery Uploadify的部分,这部分代码封装在bjui-all.js文件中, 在bjui-all.js文件中的全局变量定义中有以下

如何清空文件上传控件里的选定文件(路径)

我又来扯鸡毛蒜皮了.有名言曰人生短得不够扯鸡毛蒜皮,但我的工作就是由无数的鸡毛蒜皮组成,如之奈何? 今天的鸡毛和蒜皮是:如何清空文件上传控件里的选定文件(路径)? 场景是酱紫的: 有一个上传控件和一个按钮,其中上传控件隐藏.点击按钮,触发上传控件点击事件,于是弹出文件选择对话框:选好文件后,于是触发了上传控件的onchange事件.在这个事件里,将文件上传. 有点装逼,就是隐藏了上传控件.这可能是出于界面简约的考虑.问题是,同一个文件不能连续上传2次,因为路径不变,没有触发onchange事件.