由于ExtJS文件浏览控件(xtype:filefiled)选择文件后显示的是文件的虚拟路径c:\fakepath\***.***,无法通过获取该虚拟路径直接获取文件,所以需要将文件上传至服务器,以便获得该文件的绝对路径,然后在后台进行路径操作,以下是文件上传服务器的代码:
前台部分代码:
var
importForm=null;//文件选择框
//创建数据导入窗体
createImportForm =
function (config) {
//确定按钮
var btnOK = Ext.create('Ext.button.Button',
{
text:
'确定',
itemId:
'btnOK',
formBind:
true, //only enabled once the
form is valid
disabled:
true,
handler:
function () {
var form =
this.up('form').getForm();
this.up('window').close();
if (form.isValid()) {
form.submit({
url:
'../Ajax/ImportData/ImportExcel.ashx',
waitMsg:
'正在提交数据...',
method:
"POST",
success:
function (form, action) {
Ext.Msg.alert('信息',
uploadFileName);
}
});
}
}
});
//取消按钮
var btnCancel = Ext.create('Ext.button.Button',
{
text:
'取消',
itemId:
'btnCancel',
handler:
function () {
this.up('window').close();
}
});
if (importForm == null) {
importForm
= Ext.create('Ext.form.Panel', {
bodyPadding: 5,
buttonAlign: 'center',
url: '',
layout: 'anchor',
defaults: {
anchor: '100%'
},
autoScroll: true,
frame: true,
defaultType:
'textfield',
items: [{
xtype: 'filefield',
name: 'file',
id: 'uploadFile',
autoWidth: 'true',
labelWidth: 50,
msgTarget: 'side',
allowBlank: false,
anchor: '100%',
buttonText: '浏览',
regex:
/^.*\.(xls|xlsx)$/i,//正则表达式,用来检验文件格式
regexText:
'请选择Excel对应格式(*.xls|*.xlsx)文件!',
}],
buttons: [
btnOK, btnCancel
]
});
}
};
后台代码:
using System;
using System.Web;
public class ImportExcel : IHttpHandler {
public void
ProcessRequest (HttpContext context) {
context.Response.ContentType =
"text/plain";
HttpPostedFile file =
context.Request.Files[0];
int len = file.ContentLength;
if (len > 0 &&
!string.IsNullOrEmpty(file.FileName))
{
string
parentPath = HttpContext.Current.Server.MapPath("~/upload/");
if
(!System.IO.Directory.Exists(parentPath))
{
System.IO.Directory.CreateDirectory(parentPath);
}
file.SaveAs(System.IO.Path.Combine(parentPath,
System.IO.Path.GetFileName(file.FileName)));
}
}
public bool IsReusable
{
get {
return
false;
}
}
}
加载中,请稍候......