從今天起我會和大家一塊來學(xué)習(xí)ExtJs的典型操作,前面我寫了一些ExtJs的文章,那個(gè)系列主要是系統(tǒng)的來介紹Ext如何使用。但是我們知道如果僅僅那樣來介紹會遺漏很多實(shí)用的內(nèi)容,因此我今后會繼續(xù)寫一些常用的Ext操作方面的內(nèi)容,暫且叫做"ExtJs典型用法"系列吧。
今天我們首先看一下Ext中如何上傳文件。我們知道在傳統(tǒng)的html中有file組件(也就是type為file的input組件),但是我們也可以看到在Ext中是沒有相應(yīng)的組件的。那么我們?nèi)绾蝸砩蟼魑募??在Ext中要完成上傳其實(shí)很簡單,只需要設(shè)置FormPanel的fileUpload屬性和textfield的inputType屬性即可。好,廢話不多說,直接看代碼吧:
前臺代碼:Ext.onReady(function(){
var fpFileUpload=new Ext.FormPanel({
id:'fpFileUpload',
frame:true,
fileUpload:true,
//url:'Default.aspx',
items:[
{
xtype:'textfield',
allowBlank:false,
fieldLabel:'選擇文件',
inputType:'file',
name:'fileName'
}
],
buttonAlign:'center',
buttons:[
{
text:'上傳',
handler:function(){
if(fpFileUpload.form.isValid()){
fpFileUpload.form.submit({
method:'post',
url:'Default.aspx',
waitMsg:'文件上傳中...',
success: function() {
Ext.Msg.alert("系統(tǒng)提示", "文件上傳成功!");
},
failure: function() {
Ext.Msg.alert("系統(tǒng)提示", "文件上傳失?。?);
}
});
}else{
Ext.Msg.alert("系統(tǒng)提示","請選擇文件后再上傳!");
}
}
},
{
text:'取消',
handler:function(){
winFielUpload.hide();
}
}
]
});
var winFielUpload=new Ext.Window({
id:'win',
title:'文件上傳',
//****renderTo:'divWindow',//對于window不要使用renderTo屬性,只需要調(diào)用show方法就可以顯示,添加此屬性會難以控制其位置
width:350,
height:100,
layout:'fit',
autoDestory:true,
modal:true,
closeAction:'hide',
items:[
fpFileUpload
]
});
window.winFielUpload=winFielUpload;
});
function showWindow(){
winFielUpload.show();
}
后臺代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.Script.Serialization;
namespace FileUpload
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (Request.Files.Count == 0)
{
return;
}
else
{
HttpPostedFile file = Request.Files[0];
if (file.ContentLength > 0 && !string.IsNullOrEmpty(file.FileName))
{
file.SaveAs(Server.MapPath("/UploadFile/" + Path.GetFileName(file.FileName)));
//FileInfo fileInfo=new FileInfo(Server.MapPath("/UploadFile/" + Path.GetFileName(file.FileName)));
//JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
Response.Write("{success:true}");//前臺就是通過json中success的true活false來判斷是否成功的,切記!
}
}
}
catch (Exception ex)
{
Response.Write("{success:false}");
}
Response.End();
}
}
}
這樣就可以成功的上傳文件了
