當前位置:首頁 » 文件管理 » extjs4上傳

extjs4上傳

發布時間: 2023-08-11 17:07:26

㈠ 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這兩個就可以了

熱點內容
滑板鞋腳本視頻 發布:2025-02-02 09:48:54 瀏覽:432
群暉怎麼玩安卓模擬器 發布:2025-02-02 09:45:23 瀏覽:557
三星安卓12彩蛋怎麼玩 發布:2025-02-02 09:44:39 瀏覽:743
電腦顯示連接伺服器錯誤 發布:2025-02-02 09:24:10 瀏覽:536
瑞芯微開發板編譯 發布:2025-02-02 09:22:54 瀏覽:146
linux虛擬機用gcc編譯時顯示錯誤 發布:2025-02-02 09:14:01 瀏覽:232
java駝峰 發布:2025-02-02 09:13:26 瀏覽:651
魔獸腳本怎麼用 發布:2025-02-02 09:10:28 瀏覽:532
linuxadobe 發布:2025-02-02 09:09:43 瀏覽:212
sql2000資料庫連接 發布:2025-02-02 09:09:43 瀏覽:726