asp.net mvc + ExtJs 上传文件
刚刚接触 asp.net mvc ,ExtJs 在以前的公司用过,好长时间没用了。
今天来尝试下用asp.net mvc做服务器端,客户端用Extjs 上传文件,我用的ExtJs 是 v3.3版本的。
功能:可以上传图片(.jpg|.jpeg|.gif|.bmp|.png)和视频(.mp4|.swf|.flv|.wmv|.avi)。
Html代码:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!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>
<title>添加新品</title>
<link href="/Content/resources/css/ext-all.css" rel="stylesheet" type="text/css" />
<link href="/Content/manager.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/Scripts/ext-base.js"></script>
<script type="text/javascript" src="/Scripts/ext-all.js"></script>
<script type="text/javascript" src="/Scripts/ext-file-upload-field.js"></script>
<script type="text/javascript" src="/Scripts/common.js"></script>
<script type="text/javascript">
Ext.QuickTips.init();
Ext.onReady(loadForm);
function loadForm() {
var seasonStore = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
url: "/action/product/getseason"
}),
reader: new Ext.data.JsonReader({
totalProperty: "total",
root: "result",
fields: [{ name: 'IId' }, { name: 'VcName'}]
})
});
seasonStore.load();
var newsForm = new Ext.form.FormPanel({
title: "添加产品",
iconCls: "form-window",
labelWidth: 60,
method: 'POST',
fileUpload: true,
url: '/action/product/add',
frame: true,
layout: 'form',
width: 600,
defaults: {
allowBlank: false,
msgTarget: 'side',
anchor: '95%'
},
items: [{
xtype: 'textfield',
fieldLabel: '产品名称',
id: 'ProductName',
name: 'ProductName',
emptyText: '产品名称',
blankText: '请输入产品名称'
}, {
xtype: 'radiogroup',
fieldLabel: '产品类型',
id: 'ProductType',
anchor: '30%',
items: [{
xtype: 'radio',
name: 'ProductType',
boxLabel: '图片',
checked: true,
inputValue: '1'
}, {
xtype: 'radio',
name: 'ProductType',
boxLabel: '视频',
inputValue: '2'
}]
}, {
xtype: 'combo',
fieldLabel: '所属季节',
id: 'season',
name: 'season',
emptyText: '所属季节',
blankText: '请选择所属季节',
mode: 'local',
displayField: "VcName",
valueField: "IId",
hiddenName: "ProductSeason",
editable: false,
typeAhead: true,
forceSelection: true,
triggerAction: 'all',
selectOnFocus: true,
store: seasonStore
}, {
xtype: 'fileuploadfield',
fieldLabel: '缩略图',
name: 'ProductThumbnail',
emptyText: '缩略图',
blankText: '请选择一张图片',
buttonCfg: {
text: '',
iconCls: 'button-browser'
}
}, {
xtype: 'fileuploadfield',
fieldLabel: '图片视频',
name: 'ProductSlider',
emptyText: '图片、视频',
blankText: '请选择一个文件',
buttonCfg: {
text: '',
iconCls: 'button-browser'
}
}
],
buttons: [{
text: '保存',
width: 60,
iconCls: 'button-save',
handler: function() {
if (newsForm.getForm().isValid()) {
newsForm.form.submit({
waitMsg: '正在提交……',
success: function(form, response) {
console.log(response);
response = response.result;
if (response.success == 1) {
if (response.msg == 1) {
core.alert.info("发布成功");
form.reset();
} else if (response.msg == -1) {
core.alert.warn("您还没登录");
} else {
core.alert.error("发布失败");
}
} else {
core.alert.error(response.msg);
}
},
failure: function(form, response) {
response = response.result;
core.alert.error(response.msg);
}
});
}
}
}, {
text: '重置',
width: 60,
iconCls: 'button-reset',
handler: function() {
newsForm.form.reset();
}
}],
buttonAlign: 'center'
});
newsForm.render(document.body);
}
</script>
</head>
<body>
</body>
</html>
<!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>
<title>添加新品</title>
<link href="/Content/resources/css/ext-all.css" rel="stylesheet" type="text/css" />
<link href="/Content/manager.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/Scripts/ext-base.js"></script>
<script type="text/javascript" src="/Scripts/ext-all.js"></script>
<script type="text/javascript" src="/Scripts/ext-file-upload-field.js"></script>
<script type="text/javascript" src="/Scripts/common.js"></script>
<script type="text/javascript">
Ext.QuickTips.init();
Ext.onReady(loadForm);
function loadForm() {
var seasonStore = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
url: "/action/product/getseason"
}),
reader: new Ext.data.JsonReader({
totalProperty: "total",
root: "result",
fields: [{ name: 'IId' }, { name: 'VcName'}]
})
});
seasonStore.load();
var newsForm = new Ext.form.FormPanel({
title: "添加产品",
iconCls: "form-window",
labelWidth: 60,
method: 'POST',
fileUpload: true,
url: '/action/product/add',
frame: true,
layout: 'form',
width: 600,
defaults: {
allowBlank: false,
msgTarget: 'side',
anchor: '95%'
},
items: [{
xtype: 'textfield',
fieldLabel: '产品名称',
id: 'ProductName',
name: 'ProductName',
emptyText: '产品名称',
blankText: '请输入产品名称'
}, {
xtype: 'radiogroup',
fieldLabel: '产品类型',
id: 'ProductType',
anchor: '30%',
items: [{
xtype: 'radio',
name: 'ProductType',
boxLabel: '图片',
checked: true,
inputValue: '1'
}, {
xtype: 'radio',
name: 'ProductType',
boxLabel: '视频',
inputValue: '2'
}]
}, {
xtype: 'combo',
fieldLabel: '所属季节',
id: 'season',
name: 'season',
emptyText: '所属季节',
blankText: '请选择所属季节',
mode: 'local',
displayField: "VcName",
valueField: "IId",
hiddenName: "ProductSeason",
editable: false,
typeAhead: true,
forceSelection: true,
triggerAction: 'all',
selectOnFocus: true,
store: seasonStore
}, {
xtype: 'fileuploadfield',
fieldLabel: '缩略图',
name: 'ProductThumbnail',
emptyText: '缩略图',
blankText: '请选择一张图片',
buttonCfg: {
text: '',
iconCls: 'button-browser'
}
}, {
xtype: 'fileuploadfield',
fieldLabel: '图片视频',
name: 'ProductSlider',
emptyText: '图片、视频',
blankText: '请选择一个文件',
buttonCfg: {
text: '',
iconCls: 'button-browser'
}
}
],
buttons: [{
text: '保存',
width: 60,
iconCls: 'button-save',
handler: function() {
if (newsForm.getForm().isValid()) {
newsForm.form.submit({
waitMsg: '正在提交……',
success: function(form, response) {
console.log(response);
response = response.result;
if (response.success == 1) {
if (response.msg == 1) {
core.alert.info("发布成功");
form.reset();
} else if (response.msg == -1) {
core.alert.warn("您还没登录");
} else {
core.alert.error("发布失败");
}
} else {
core.alert.error(response.msg);
}
},
failure: function(form, response) {
response = response.result;
core.alert.error(response.msg);
}
});
}
}
}, {
text: '重置',
width: 60,
iconCls: 'button-reset',
handler: function() {
newsForm.form.reset();
}
}],
buttonAlign: 'center'
});
newsForm.render(document.body);
}
</script>
</head>
<body>
</body>
</html>
运行起来的html页面如下图:
Controller 服务器端代码:
/// <summary> /// 产品接口 /// </summary> /// <param name="id">请求参数</param> public ActionResult Product(string id) { object objJson = base.SetError(this.output); if (base.CurrentUser != null) { switch (id.ToLower()) { #region 添加产品 case "add": try { int pType = 1; int.TryParse(Request.Form["ProductType"], out pType); DateTime dtCreateDate = DateTime.Now; string fileName = Core.GetDateToString(dtCreateDate); HttpPostedFileBase pThumbnail = Request.Files["ProductThumbnail"]; HttpPostedFileBase pSlider = Request.Files["ProductSlider"]; string thumbnailRootPath = "/image/product/thumbnail/", sliderRootPath = "/image/product/slider/"; string thumbnailSavePath = this.UploadFile(thumbnailRootPath, fileName, pThumbnail, false, 120); if (thumbnailSavePath != string.Empty) { string[] array = pType == 1 ? Core.GetPictureExtension() : Core.GetVideoExtension(); string sliderSavePath = this.UploadFile(sliderRootPath, fileName, pSlider, array, pType == 1 ? 2048 : 3072); if (sliderSavePath != string.Empty) { string pName = Request.Form["ProductName"]; int seasonId = 0; int.TryParse(Request.Form["ProductSeason"], out seasonId); long productId = this.productBusiness.CreateProduct(pName, pType, seasonId, thumbnailSavePath, sliderSavePath, dtCreateDate); if (productId > 0) { objJson = base.SetMessage(1);//1 } else { objJson = base.SetMessage(0);//0 } } else { objJson = base.SetError("上传幻灯片失败"); } } else { objJson = base.SetError("上传缩略图失败"); } } catch (ValidationException vex) { objJson = base.SetError(vex.Message); } catch (Exception ex) { objJson = base.SetError(ex.Message); } break;
#endregion
default: break; } } else { //objJson = base.SetErrorMessage("您还没登录"); } return Content(base.GenerateJson(objJson)); }
特别注意:
由于asp.net mvc 默认情况下限制上传文件大小为4MB,通过修改web.config文件来改变应用程序上传限制
在web.config的<system.web>节点中加入 <httpRuntime maxRequestLength="10240" executionTimeout="200" enable="true" />
maxRequestLength: 设置上传文件大小,单位是kb. 我设置了10M 兆
executionTimeout: 允许执行请求的最大秒数,此功能必须在Compilation元素中Debug属性为false时才生效.
enable: 指定是否在当前的节点及子节点级别启用应用程序域 (AppDomain),以接受传入的请求。如果为 False,则实际上关闭了该应用程序。默认值为 True.
OK了,运行起来:
寄语:希望喜欢asp.net mvc 的朋友和我交流。o(∩_∩)o