extjs4上传
㈠ ExtJs中的文件上传下载功能求教,100分
http://hi..com/%B1%F9%C3%CE%CE%DE%BA%DB/blog/item/3b19542954c90ff799250a29.html
前台EXT(假设上传文件为2个):主要就是个formPanel,items中写为:
{
xtype : 'textfield',
fieldLabel : '上传文件1',
name : 'file',
inputType : 'file'
}, {
xtype : 'textfield',
fieldLabel : '上传文件2',
name : 'file',
inputType : 'file'
}
其他地方不详细诉说了,不明白看EXT表单提交去,别忘记fileUpload : true就可以了
注意:因为是用struts2处理,name都是一样的file
struts2后台:
private List<File> file;对应前面的name
// 使用列表保存多个上传文件的文件名
private List<String> fileFileName;
// 使用列表保存多个上传文件的MIME类型
private List<String> fileContentType;
// 保存上传文件的目录,相对于Web应用程序的根路径,在struts.xml文件中配置
private String uploadDir;
get/set方法略
public void fileUpLoad() {
String newFileName = null;
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
String reInfo="";//上传成功返回的东西
for (int i = 0; i < file.size(); i++) {
long now = new Date().getTime();
int index = fileFileName.get(i).lastIndexOf('.');
String path = ServletActionContext.getServletContext().getRealPath(
uploadDir);
File dir = new File(path);
if (!dir.exists())
dir.mkdir();//创建个文件夹
if (index != -1)
newFileName = fileFileName.get(i).substring(0, index) + "-"
+ now + fileFileName.get(i).substring(index);//生成新文件名
else
newFileName = fileFileName.get(i) + "-" + now;
reInfo+=newFileName+"@";
bos = null;
bis = null;
try {
FileInputStream fis = new FileInputStream(file.get(i)); // /////////
bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(new File(dir,
newFileName));
bos = new BufferedOutputStream(fos);
byte[] buf = new byte[4096];
int len = -1;
while ((len = bis.read(buf)) != -1) {
bos.write(buf, 0, len);
}
} catch (Exception e) {
/////错误返回
try {
HttpServletResponse response = ApplicationWebRequestContext
.getWebApplicationContext().getResponse();
String msg = "{success:false,errors:{name:'上传错误'}}";
response.getWriter().write(msg);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
////////
} finally {
////////////////////////善后
try {
if (null != bis)
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (null != bos)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
////////////////////////////////
}
//最后若没错误返回就这里返回了
try {
HttpServletResponse response = ApplicationWebRequestContext
.getWebApplicationContext().getResponse();
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
String msg = "{success:true,msg:'"+reInfo+"'}";
response.getWriter().write(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
改方法参考了孙鑫的strut2深入详解,自己修改而成
注意上面2个黑体,尤其是第2行,不加的话浏览器会很悲剧的再你上传陈宫以后的返回前后加上<pre>,于是ext表单获得返回失败,这就是为什么有些人用其他EXT上传组件时候上传成功一直卡成进度条那
㈡ extjs 3.4中 怎么给htmlEdit添加图片插件 实现图片上传功能
首先要使用extjs自带的HTMLEditor,然后在原有的工具条上添加一个图片按钮,点击这个图片按钮要弹出窗口,这个窗口负责实现上传功能,实现上传后,要将上传的图片路径添加到HTMLEditor的光标处,并且要以<IMG></IMG>的方式,这样HTMLEditor才能解析出来。实现代码如下:
前台JSP页面
fieldLabel : '商品特性',
id : 'shopSp.spTxms',
name : 'shopSp.spTxms',
xtype : 'StarHtmleditor',
anchor : '93%'
这其中引用了StarHtmleditor,StarHtmleditor.js的代码如下,直接将代码复制下来,然后新建个JS,全复制进去就行了。
var HTMLEditor = Ext.extend(Ext.form.HtmlEditor, {
addImage : function() {
var editor = this;
var imgform = new Ext.FormPanel({
region : 'center',
labelWidth : 55,
frame : true,
bodyStyle : 'padding:5px 5px 0',
autoScroll : true,
border : false,
fileUpload : true,
items : [{
xtype : 'textfield',
fieldLabel : '选择文件',
id : 'UserFile',
name : 'UserFile',
inputType : 'file',
allowBlank : false,
blankText : '文件不能为空',
anchor : '90%'
}],
buttons : [{
text : '上传',
handler : function() {
if (!imgform.form.isValid()) {return;}
imgform.form.submit({
waitMsg : '正在上传......',
url : 'HTMLEditorAddImgCommonAction.action',
success : function(form, action) {
var element = document.createElement("img");
element.src = action.result.fileURL;
if (Ext.isIE) {
editor.insertAtCursor(element.outerHTML);
} else {
var selection = editor.win.getSelection();
if (!selection.isCollapsed) {
selection.deleteFromDocument();
}
selection.getRangeAt(0).insertNode(element);
}
//win.hide();//原始方法,但只能传一个图片
//更新后的方法
form.reset();
win.close();
},
failure : function(form, action) {
form.reset();
if (action.failureType == Ext.form.Action.SERVER_INVALID)
Ext.MessageBox.alert('警告','上传失败',action.result.errors.msg);
}
});
}
}, {
text : '关闭',
handler : function() {
win.close(this);
}
}]
})
var win = new Ext.Window({
title : "上传图片",
width : 300,
height : 200,
modal : true,
border : false,
iconCls : "picture.png",
layout : "fit",
items : imgform
});
win.show();
},
createToolbar : function(editor) {
HTMLEditor.superclass.createToolbar.call(this, editor);
this.tb.insertButton(16, {
cls : "x-btn-icon",
icon : "picture.png",
handler : this.addImage,
scope : this
});
}
});
Ext.reg('StarHtmleditor', HTMLEditor);
JS的第一句var HTMLEditor = Ext.extend(Ext.form.HtmlEditor, 网上是没有var的,不用var不知道为什么总是报错,另外JS一定要与JSP的编码方式一致,要不然报莫名其妙的错误,而且错误都没有显示。
后台java代码
/****
* HTMLEditor增加上传图片功能:
* 1、上传图片后,需要将图片的位置及图片的名称返回给前台HTMLEditor
* 2、前台HTMLEditor根据返回的值将图片显示出来
* 3、进行统一保存
* @param 上传图片功能
* @return JSON结果
* @throws IOException
*/
public void HTMLEditorAddImg() throws IOException {
if(!"".equals(UserFile) && UserFile != null && UserFile.length() > 0){
File path = ImportImg(UserFile, "jpg");
UserFilePath = "../" + path.toString().replaceAll("\\", "/").substring(path.toString().replaceAll("\\", "/").indexOf("FileImg"));
}
this.getResponse().setContentType("text/html");
this.getResponse().getWriter().write("{success:'true',fileURL:'" + UserFilePath + "'}");
}
特别要注意的是路径问题,路径问题主要有2点需要注意:
1、前台页面引用StarHtmleditor.js的路径一定要正确;
2、Htmleditor上传的图片路径一定要改,因为上传之后图片路径变为http://localhost:8080/,在正常使用中图片不显示,要将该地址替换为服务器的IP地址;替换方法如下:
//获取本地IP地址,因为extjs的htmleditor上传的照片路径有问题,需要将路径替换为本机IP地址
InetAddress inet = InetAddress.getLocalHost();
shopSp.setSpTxms(shopSp.getSpTxms().replace("localhost", inet.getHostAddress().toString()));
这样基本就完成了这个HTMLEditor上传图片功能。
如图:
㈢ ExtJs中怎么上传文件
下面为大家介绍在ExtJs中上传文件的几种方法
第一种方法:传统的上传方式
在formpanal中增加一个fileUpload的属性
例子代码:
JScript 代码 复制
Ext.onReady(function(){
var form = new Ext.form.FormPanel({
renderTo:'file',
labelAlign: 'right',
title: '文件上传',
labelWidth: 60,
frame:true,
url: 服务器处理上传功能的url地址,//fileUploadServlet
width: 300,
height:200,
fileUpload: true,
items: [{
xtype: 'textfield',
fieldLabel: '文件名',
name: 'file',
inputType: 'file'//文件类型
}],
buttons: [{
text: '上传',
handler: function() {
form.getForm().submit({
success: function(form, response){
Ext.Msg.alert('信息', response.result.msg);
},
failure: function(){
Ext.Msg.alert('错误', '文件上传失败');
}
});
}
}]
});
});
第二种方法:借助Ext.ux.UploadDialog.Dialog的组件,在编码时需要导入两个文件
需要引入 Ext.ux.UploadDialog 样式文件 和 Ext.ux.UploadDialog.packed脚本文件。
例子代码
//在使用此方法进行文件上传时,其后台往页面的返回值类型是这样的:
//{'success':true,'message':'上传成功'}
//如果没有success:true,无论上传成功与否,显示的都是上传失败,其实这个和form.submit()的提交方式是一个道理。
var dialog = new Ext.ux.UploadDialog.Dialog({
autoCreate: true,
closable: true,
collapsible: false,
draggable: true,
minWidth: 400,
minHeight: 200,
width: 400,
height: 350,
permitted_extensions:['JPG','jpg','jpeg','JPEG','GIF','gif','xls','XLS'],
proxyDrag: true,
resizable: true,
constraintoviewport: true,
title: '文件上传',
url:用于处理上传文件功能的Url,
reset_on_hide: false,
allow_close_on_upload: true ,
upload_autostart: false
});
//定义上传文件的按钮
var btnShow = new Ext.Button({
text:'上传文件',
listeners:{
click:function(btnThis,eventobj){
dialog.show();
}
}
});
㈣ extjs怎样做图片上传
1.代码如下:
复制代码
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <title></title>
5 <!--ExtJs框架开始-->
6 <script type="text/javascript" src="/Ext/adapter/ext/ext-base.js"></script>
7 <script type="text/javascript" src="/Ext/ext-all.js"></script>
8 <script src="/Ext/src/locale/ext-lang-zh_CN.js" type="text/javascript"></script>
9 <link rel="stylesheet" type="text/css" href="/Ext/resources/css/ext-all.css" />
10 <!--ExtJs框架结束-->
11 <script type="text/javascript">
12 Ext.onReady(function () {
13 //初始化标签中的Ext:Qtip属性。
14 Ext.QuickTips.init();
15 Ext.form.Field.prototype.msgTarget = 'side';
16 //创建div组件
17 var imagebox = new Ext.BoxComponent({
18 autoEl: {
19 style: 'width:150px;height:150px;margin:0px auto;border:1px solid #ccc; text-align:center;padding-top:20px;margin-bottom:10px',
20 tag: 'div',
21 id: 'imageshow',
22 html: '暂无图片'
23 }
24 });
25 //创建文本上传域
26 var file = new Ext.form.TextField({
27 name: 'imgFile',
28 fieldLabel: '文件上传',
29 inputType: 'file',
30 allowBlank: false,
31 blankText: '请浏览图片'
32 });
33 //提交按钮处理方法
34 var btnsubmitclick = function () {
35 if (form.getForm().isValid()) {
36 form.getForm().submit({
37 waitTitle: "请稍候",
38 waitMsg: '正在上传...',
39 success: function (form, action) {
40 Ext.MessageBox.alert("提示", "上传成功!");
41 document.getElementById('imageshow').innerHTML = '<img style="width:150px;height:150px" src="' + action.result.path + '"/>';
42 },
43 failure: function () {
44 Ext.MessageBox.alert("提示", "上传失败!");
45 }
46 });
47 }
48 }
49 //重置按钮"点击时"处理方法
50 var btnresetclick = function () {
51 form.getForm().reset();
52 }
53 //表单
54 var form = new Ext.form.FormPanel({
55 frame: true,
56 fileUpload: true,
57 url: '/App_Ashx/Demo/Upload.ashx',
58 title: '表单标题',
59 style: 'margin:10px',
60 items: [imagebox, file],
61 buttons: [{
62 text: '保存',
63 handler: btnsubmitclick
64 }, {
65 text: '重置',
66 handler: btnresetclick
67 }]
68 });
69 //窗体
70 var win = new Ext.Window({
71 title: '窗口',
72 width: 476,
73 height: 374,
74 resizable: true,
75 modal: true,
76 closable: true,
77 maximizable: true,
78 minimizable: true,
79 buttonAlign: 'center',
80 items: form
81 });
82 win.show();
83 });
84 </script>
85 </head>
86 <body>
87 <!--
88 说明:
89 (1)var imagebox = new Ext.BoxComponent():创建一个新的html标记。
90 官方解释如下:
91 This may then be added to a Container as a child item.
92 To create a BoxComponent based around a HTML element to be created at render time, use the autoEl config option which takes the form of a DomHelper specification:
93 (2) autoEl: {style: '',tag: 'div',id: 'imageshow', html: '暂无图片'}定义这个html标记的属性,如 标记为:div,id是多少等。
94 官方实例为:
95 var myImage = new Ext.BoxComponent({
96 autoEl: {
97 tag: 'img',
98 src: '/images/my-image.jpg'
99 }
100 });
101 (3)var file = new Ext.form.TextField():创建一个新的文件上传域。
102 (4)name: 'imgFile':名称,重要,因为service端要根据这个名称接收图片。
103 (5)inputType: 'file':表单类型为文件类型。
104 (6)waitTitle: "请稍候",waitMsg: '正在上传...',:上传等待过程中的提示信息。
105 (7)document.getElementById('imageshow').innerHTML = '<img style="width:150px;height:150px" src="' + action.result.path + '"/>';这个是原生态的js,把imageshow的值换成图片。
106 -->
107 </body>
108 </html>
复制代码
其中与service交互用上传图片的 一般处理程序文件,源码如下:
/App_Ashx/Demo/Upload.ashx
复制代码
1 using System;
2 using System.Web;
3 using System.IO;
4 using System.Globalization;
5
6 namespace HZYT.ExtJs.WebSite.App_Ashx.Demo
7 {
8 public class Upload : IHttpHandler
9 {
10 public void ProcessRequest(HttpContext context)
11 {
12 //虚拟目录,建议写在配置文件中
13 String strPath = "/Upload/Image/";
14 //文件本地目录
15 String dirPath = context.Server.MapPath(strPath);
16 //接收文件
17 HttpPostedFile imgFile = context.Request.Files["imgFile"];
18 //取出文件扩展名
19 String fileExt = Path.GetExtension(imgFile.FileName).ToLower();
20 //重新命名文件
21 String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
22 //文件上传路径
23 String filePath = dirPath + newFileName;
24 //保存文件
25 imgFile.SaveAs(filePath);
26 //客户端输出
27 context.Response.Write("{success:true,path:'" + strPath + newFileName + "'}");
28 }
29
30 public bool IsReusable
31 {
32 get
33 {
34 return false;
35 }
36 }
37 }
38 }
复制代码
2.效果如下:
无废话extjs
3.说明:
(1)上传域不光可以上传图片,还要以上传其他文件。这里我们以图片为例。
(2)在实际开发中,我们还要对图片格式,大小等进行校验,这个示例测重于上传,没有加入任何校验。
㈤ 我想用extjs实现上传和下载
给你上传代码,下载在服务端实现
重点是 xtype: 'filefield',
*************************************************************************
*上传框组件
*
************************************************************************
*/
Ext.define('Mocoolka.web.coreview.container.MKUploadForm', {
extend:'Ext.form.Panel',
frame: true,
autoScroll: true,
initComponent: function () {
var me = this;
me.title = getUIWithID("SystemUI.Buttons.Upload.Description");//'上传',
me.items = [
{
xtype: 'filefield',
emptyText: getUIWithID("SystemUI.MKUploadForm.SelectFile.Description"),//'选择一个文件',
name: 'filename',
buttonText: '...',
buttonConfig: {
iconCls: 'upload-icon'
}
},
];
me.buttons = [{
text: getUIWithID("SystemUI.Buttons.Upload.Description"),//'上传',
handler: function () {
var form = this.up('form').getForm();
var action = this.up('form').mkaction;
var myaction = "import";
if (action.get("Name") == "ImportAttachment")
myaction = "ImportAttachment";
var url = mkruntimer.getDataManager().getUrlPath(myaction, action);
if (form.isValid()) {
form.submit({
url: url,
waitMsg: getUIWithID("SystemUI.Buttons.Uploading.Description"),//'上传中...',
success: function (fp, o) {
var form1 = form.owner;
form1.mkcallout(form1.mkcalloutpara, action.result.children);
form1.up('window').close();
},
failure: function (form, action) {
mkerrorutil.processAjaxFailure(action.response);
}
});
}
}
}, {
text: getUIWithID("SystemUI.Buttons.Reset.Description"),//'重设',
handler: function () {
this.up('form').getForm().reset();
}
}, {
text: getUIWithID("SystemUI.Buttons.Cancel.Description"),//'取消',
handler: function () {
this.up('window').close();
}
},
{
text: getUIWithID("SystemUI.MKUploadForm.AddFile.Description"),//'增加一个文件',
handler: function () {
this.up('form').addFile();
}
}
]
me.callParent(arguments);
},
addFile: function () {
var me = this;
me.add({
xtype: 'filefield',
emptyText: getUIWithID("SystemUI.MKUploadForm.SelectFile.Description"),//'选择一个文件',
fieldLabel: getUIWithID(""),// '文件',
name: 'filename',
buttonText: '',
buttonConfig: {
iconCls: 'upload-icon'
}
});
},
//standardSubmit:false,
bodyPadding: '10 10 0',
flex:1,
defaults: {
anchor: '100%',
msgTarget: 'side',
labelWidth: 50
},
region: 'center',
});
㈥ 谁做过ExtJS上传下载文件的功能,求教
//附件上传表单
varwareFrom=Ext.create('Ext.form.Panel',{
items:[{
xtype:'filefield',
name:'upfile',
fieldLabel:'文件上传',
blankText:'请选择文件',
allowBlank:false
}]
});
//创建一个窗体
varwin=Ext.create('Ext.window.Window',{
title:'上传课件',
width:'auto',
height:'auto',
layout:'fit',
items:wareFrom,
buttonAlign:'center',
buttons:[{
minWidth:80,
text:'取消',
handler:function(){ win.hide(); }
},{
minWidth:80,
text:'上传',
handler:upLoad
}]
});
//显示窗体
win.show();
//点击上传按钮处理事件
functionupLoad(){
if(wareFrom.getForm().isValid()){
wareFrom.getForm().submit({
waitTitle:'请稍候',
waitMsg:'正在执行操作...',
url:'upload.php?upload=ok',
method:'POST',
success:function(form,action){
Ext.Msg.alert('提示',action.result.msg);
wareFrom.getForm().reset();
},
failure:function(form,action){
Ext.Msg.alert('提示',action.result.msg);
}
});
}
}
//后台不管你用的什么,流程一致,此以php为例,因为比较好写
<?php
if($_GET['upload']=='ok'){
//上传路径
$location='upload_file/';
//此处的name是上传窗体,upload控件的name
if(move_uploaded_file($_FILES['upfile']['tmp_name'],$location)){
echojson_encode(array('success'=>true,'msg'=>'上传成功'));
}else{
echojson_encode(array('success'=>false,'msg'=>'上传发生了错误'));
}
}
?>
//下载
<?php
//此处需前台传一个id过来
$id=$_GET['id'];
$sql="SELECT*FROM`ware`WHERE`id`='$id'";
$result=mysql_query($sql);
$row=mysql_fetch_row($result);
//此处的row是文件保存在数据库的路径
if(file_exists($row[0])){
//用stream读取该文件
$file=fopen($row[0],'r');
header('Content-Type:application/octet-stream');
header('Accept-Ranges:bytes');
header('Accept-Length:'.filesize($row[0]));
//此处的row1是文件名称
header('Content-Disposition:attachment;filename='.$row[1]);
echofread($file,filesize($row[0]));
fclose($file);
}
?>
//有什么地方不明白的话,欢迎继续追问
㈦ 我用extjs做项目时用到了上传,属性 inputType : "file",结果在做修改时取不到路径,为空,怎么才能取到
// 文件上传
var fp = new Ext.form.FormPanel({
region : 'south',
fileUpload : true,
collapsible : true,
frame : true,
title : '上传文件到服务器',
autoHeight : true,
bodyStyle : 'padding: 8px 10px 0 10px;',
labelWidth : 100,
labelAlign : 'right',
defaults : {
anchor : '95%',
msgTarget : 'side'
},
items : [{
allowBlank : true,
emptyText : '可重命名文件名',
xtype : 'textfield',
fieldLabel : '文件名称',
name : 'fileName'
}, {
allowBlank : false,
xtype : 'fileuploadfield',
emptyText : '请选择要上传的文件',
fieldLabel : '文件地址',
name : 'formFile',
buttonText : '浏览...',
buttonCfg : {
iconCls : 'upload-icon'
}
}],
buttons : [{
text : '保存',
handler : function() {
if (fp.getForm().isValid()) {
fp.getForm().submit({
url : '/sparta/managefile.do?op=upLoadFile',
waitMsg : '正在上传文件中...',
success : function() {
Ext.example.msg('消息提示',
'文件上传成功!');
fileStore.reload();
},
failure : function() {
Ext.example.msg('消息提示',
'文件上传失败!');
}
});
}
}
}, {
text : '重置',
handler : function() {
fp.getForm().reset();
}
}]
});
这是我写的可以重命名上传文件的上传工具栏,
你可以参考下,直接拷贝进去就可以用,
后台获取fileName和formFile这两个就可以了