extjs java 上传文件_Extjs 上传文件(二)

本文展示了如何使用ExtJS和Java进行文件上传。通过创建一个ExtJS表单,包含文件上传字段和组合框选择文档类型,利用Java处理上传的文件并将其存储到数据库。在后台,文件信息被解析并根据文件类型创建索引。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天突然想起来以前的关于EXT的上传的文章没有贴出来,现在贴出代码在此

Js代码 icon_copy.gificon_star.png

spinner.gifvar uploadForm= new Ext.FormPanel({

id: 'form-panel',

fileUpload: true,

width: 500,

frame: true,

//title: '流程文件上传',

collapsible:true,

autoHeight: true,

bodyStyle: 'padding: 10px 10px 0 10px;',

labelWidth: 50,

defaults: {

anchor: '95%',

allowBlank: false,

msgTarget: 'side'

},

items: [{

xtype:'combo',

width : 200,

allowBlank : false,

blankText : '必须选择文档类型',

hiddenName : 'CId', //这个hiddenName指的就是BookTypeId

name : 'CName',

store : new Ext.data.Store({

autoLoad :true,

reader: new Ext.data.JsonReader({//读取json数据

root:'TCategoryList',                        //

totalProperty:'totalProperty',  //总记录数

id:'CId'

},

Ext.data.Record.create([

{name: 'CId'},

{name: 'CName'}

])

),

proxy : new Ext.data.HttpProxy({

url : path+'doc/getTCategoryForDoc.action'

})

}),//设置数据源

allQuery:'alldoc',//查询全部信息的查询字符串

triggerAction: 'all',//单击触发按钮显示全部数据

editable : false,//禁止编辑

loadingText : '正在加载文档类型信息',//加载数据时显示的提示信息

displayField:'CName',//定义要显示的字段

valueField : 'CId',

emptyText :'请选择文档类型',

mode: 'remote',//远程模式

id:'CName',

fieldLabel:'类型'

},{

xtype: 'fileuploadfield',

id: 'form-file',

emptyText: '请选择流程文件...',

fieldLabel: '文件',

name: 'upload',     // ★ from字段,对应后台java的bean属性,上传的文件字段

buttonCfg: {

text: '',  // 上传文件时的本地查找按钮

iconCls: 'icon-upload'// 按钮上的图片,定义在CSS中

}

},

{

xtype: 'hidden',

id: 'fileName',

emptyText: '请选择文档文件...',

name: 'fileName',

text:Ext.getCmp("form-file") //在上传这个框中,getCmp可以获取整条路径的最后的名称

},

{

xtype:'hidden',

name : 'docId',

id:'docId'

}

],

buttons: [{

text: '上传',

handler: function(){

if(uploadForm.getForm().isValid()){

uploadForm.getForm().submit({

url:path+ 'upload/upload.action?Tab_staffId='+staffId,

method:'POST',

waitTitle: '请稍后',

waitMsg: '正在上传文档文件 ...',

success: function(fp, action){

updatedocListForUpload(action.result.docId,action.result.name,action.result.docUrl,action.result.CName,action.result.extType,action.result.state);

msg('成功!', '文档文件上传成功!');

//msg("返回的ID呢"+action.result.docId);

//Ext.log('上传成功。')

//Ext.log(action.failure)

//failure

//Ext.log(action.result.upload);

//Ext.log(action.result.msg);

Ext.getCmp("form-file").reset();          // 指定文件字段的id清空其内容

Ext.getCmp("CName").reset();

},

failure: function(fp, action){

msg('失败!', '文档文件上传失败!');

}

});

}

}

},{

text: '重置',

handler: function(){

uploadForm.getForm().reset();

}

}]

});var uploadForm= new Ext.FormPanel({    id: 'form-panel',            fileUpload: true,            width: 500,            frame: true,            //title: '流程文件上传',            collapsible:true,            autoHeight: true,            bodyStyle: 'padding: 10px 10px 0 10px;',            labelWidth: 50,            defaults: {                anchor: '95%',                allowBlank: false,                msgTarget: 'side'            },            items: [{xtype:'combo',width : 200,allowBlank : false,blankText : '必须选择文档类型',hiddenName : 'CId', //这个hiddenName指的就是BookTypeIdname : 'CName',store : new Ext.data.Store({autoLoad :true, reader: new Ext.data.JsonReader({//读取json数据                   root:'TCategoryList',                        //                   totalProperty:'totalProperty',  //总记录数                   id:'CId'                                 },Ext.data.Record.create([{name: 'CId'},{name: 'CName'}])),proxy : new Ext.data.HttpProxy({url : path+'doc/getTCategoryForDoc.action'})}),//设置数据源allQuery:'alldoc',//查询全部信息的查询字符串triggerAction: 'all',//单击触发按钮显示全部数据editable : false,//禁止编辑loadingText : '正在加载文档类型信息',//加载数据时显示的提示信息displayField:'CName',//定义要显示的字段valueField : 'CId',emptyText :'请选择文档类型',mode: 'remote',//远程模式id:'CName',fieldLabel:'类型'},{                xtype: 'fileuploadfield',                id: 'form-file',                emptyText: '请选择流程文件...',                fieldLabel: '文件',                name: 'upload', // ★ from字段,对应后台java的bean属性,上传的文件字段                buttonCfg: {    text: '',  // 上传文件时的本地查找按钮                    iconCls: 'icon-upload'  // 按钮上的图片,定义在CSS中                }            },            {                    xtype: 'hidden',                    id: 'fileName',                    emptyText: '请选择文档文件...',                    name: 'fileName',                    text:Ext.getCmp("form-file") //在上传这个框中,getCmp可以获取整条路径的最后的名称                                  },              {               xtype:'hidden',               name : 'docId',               id:'docId'               }           ],    buttons: [{                text: '上传',                handler: function(){                        if(uploadForm.getForm().isValid()){                    uploadForm.getForm().submit({                        url:path+ 'upload/upload.action?Tab_staffId='+staffId,                        method:'POST',        waitTitle: '请稍后',                        waitMsg: '正在上传文档文件 ...',    success: function(fp, action){                    updatedocListForUpload(action.result.docId,action.result.name,action.result.docUrl,action.result.CName,action.result.extType,action.result.state);                       msg('成功!', '文档文件上传成功!');                       //msg("返回的ID呢"+action.result.docId);           //Ext.log('上传成功。')    //Ext.log(action.failure)    //failure    //Ext.log(action.result.upload);    //Ext.log(action.result.msg);                            Ext.getCmp("form-file").reset();          // 指定文件字段的id清空其内容    Ext.getCmp("CName").reset();                        },    failure: function(fp, action){                            msg('失败!', '文档文件上传失败!');                        }                     });                    }                }            },{                text: '重置',                handler: function(){            uploadForm.getForm().reset();                }            }]        });

具体处理的ACTION

Java代码 icon_copy.gificon_star.png

spinner.gifpackage lsbpm.web.action;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.net.URLEncoder;

import java.sql.Timestamp;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.UUID;

import lsbpm.db.domain2.TCategory;

import lsbpm.db.domain2.TDoc;

import lsbpm.db.domain2.TDocCategory;

import lsbpm.db.domain2.TStaff;

import lsbpm.web.lecene.LuceneIndex;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

/**

* Show case File Upload example's action. FileUploadAction

*/

publicclass FileUploadAction extends BaseAction {

privatestaticfinallong serialVersionUID = 5156288255337069381L;

private String contentType;

private File upload;

private String fileName;

private String caption;

private String CId;//文档TCategory的ID

private String jsonMsg;// 返回ExtJs upload form消息

private String Tab_staffId;

public String getJsonMsg() {

return jsonMsg;

}

publicvoid setJsonMsg(String jsonMsg) {

this.jsonMsg = jsonMsg;

}

// since we are using the file name will be

// obtained through getter/setter of FileName

public String getUploadFileName() {

return fileName;

}

publicvoid setUploadFileName(String fileName) {

this.fileName = fileName;

}

// since we are using the content type will be

// obtained through getter/setter of ContentType

public String getUploadContentType() {

return contentType;

}

publicvoid setUploadContentType(String contentType) {

this.contentType = contentType;

}

// since we are using the File itself will be

// obtained through getter/setter of

public File getUpload() {

return upload;

}

publicvoid setUpload(File upload) {

this.upload = upload;

}

public String getCaption() {

return caption;

}

publicvoid setCaption(String caption) {

this.caption = caption;

}

// 解析上传的流程文件,将流程图分解后存入数据库中

// 用json格式返回成功失败及错误信息等,可直接与ExtJS衔接。

public String combinStr(String str,int i){

str=str.substring(0,str.indexOf("."))+i+ str.substring(str.indexOf("."));

return str;

}

public String upload() throws Exception {

System.out.println("执行上传文件操作。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。");

// 定义要返回的对象,返回时用json包装

HashMap retMsg = new HashMap();

TStaff staff=(TStaff)genericService.findById(TStaff.class, Tab_staffId);

TCategory category=(TCategory)genericService.findById(TCategory.class, CId);

TDoc doc = new TDoc();

doc.setName(fileName);//-------------------------------------------------(1)filename属性(非空)

System.out.println("拼装前------------------>"+fileName);

List propertisList=new ArrayList();

propertisList.add("docVersion-");

List result=genericService.findByProperty(doc, propertisList, 0, 0);

doc.setDocVersion(1);//-------------------------------------------------(2)DocVersion属性(非空)

int size=propertisList==null?0:result.size();

if(size>0){

int docVersion=result.get(0).getDocVersion();

doc.setDocVersion(docVersion+1);

fileName=combinStr(fileName,docVersion+1);主要针对相同名称的文件处理加上版本号

System.out.println("--------------------经过版本升级---------------------------------");

}

doc.setDocAlias(fileName);//-------------------------------------------------(3)DocAlias属性(非空)

doc.setBoost(0d);//-------------------------------------------------(4)Broost属性(非空)

System.out.println("拼装后----------------->"+fileName);

String realPath="E:\\DataDir\\"+fileName;

if (upload.isFile()) {

BufferedInputStream bis = new BufferedInputStream(

new FileInputStream(upload));

BufferedOutputStream bos = null;

try {

bos = new BufferedOutputStream(new FileOutputStream(realPath));//为以防万一,以后写文件的路径尽量写成正双斜杠的

// 从源文件中取数据,写到目标文件中

byte[] buff = newbyte[8192];

for (int len = -1; (len = bis.read(buff)) != -1;) {

bos.write(buff, 0, len);

}

bos.flush();

} catch (IOException ie) {

ie.printStackTrace();

} finally {

if (bis != null) {

try {

bis.close();

} catch (IOException ie) {

ie.printStackTrace();

}

}

if (bos != null) {

try {

bos.close();

} catch (IOException ie) {

ie.printStackTrace();

}

}

}

System.out.println("----------------------------0000");

doc.setDocUrl(fileName);//-------------------------------------------------(5)DocUrl属性(非空)

doc.setExtType(fileName.substring(fileName.lastIndexOf('.')+1));//---------(6)extType属性(非空)

doc.setState("可用");//状态这个暂时写死为可用 //----------------------------------(7)state属性(非空)

doc.setTStaffByDesigner(staff);//设计者先和操作者暂定为同一人-------------------- (8)designer属性(可空)

doc.setTStaffByOperator(staff);//------------------------------------------(9)operator属性(非空)

doc.setUpgradeDate(new Timestamp(System.currentTimeMillis()));

boolean isSuccess = false;

System.out.println("即将要插入数据库的文件内容为:"+doc);

genericService.create(doc);

//插入文档类型

TDocCategory cate=new TDocCategory();

cate.setTCategory(category);

cate.setTDoc(doc);

cate.setBoost(0d);

genericService.create(cate);

String Id = doc.getDocId();

System.out.println("新增后获取到的员工ID" + Id);

System.out.println(fileName + "----------------");

String extTypes=doc.getExtType();

//如果上传的文件在我要建立索引的范围之内,可以见索引,否则不建立

if(extTypes.equals("pdf")||extTypes.equals("html")||

extTypes.equals("rtf")||extTypes.equals("doc")||

extTypes.equals("ppt")||extTypes.equals("xls")||

extTypes.equals("txt")){

LuceneIndex index=new LuceneIndex();//建立索引

index.buildsingle(doc);

System.out.println("索引完毕。。。。。。。。。。。。。。。。。。。。。");

}

// 流程文件解析和加载,成功! 将流打到客户端

retMsg.put("success", "true");

retMsg.put("docId", Id);

retMsg.put("name", doc.getDocAlias());

if(doc.getTDocCategories().size()==1){

for(TDocCategory cate1:doc.getTDocCategories()){

retMsg.put("CName",cate1.getTCategory().getName());

}

}

retMsg.put("extType", doc.getExtType());

retMsg.put("state", doc.getState());

retMsg.put("docId", doc.getDocId());

retMsg.put("docUrl", doc.getDocUrl());

retMsg.put("upload", "ok");

retMsg.put("msg", "hhaahhaa!!");

} else {

// 流程文件解析和加载,失败!

retMsg.put("failure", "true");

retMsg.put("upload", "error");

retMsg.put("msg", " failed !!");

}

// json包装返回对象

jsonMsg = JSONObject.fromObject(retMsg).toString();

return SUCCESS;

}

public String getFileName() {

return fileName;

}

publicvoid setFileName(String fileName) {

this.fileName = fileName;

}

public String getCId() {

return CId;

}

publicvoid setCId(String cId) {

CId = cId;

}

public String getTab_staffId() {

return Tab_staffId;

}

publicvoid setTab_staffId(String tabStaffId) {

Tab_staffId = tabStaffId;

}

}

package lsbpm.web.action;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.net.URLEncoder;import java.sql.Timestamp;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.UUID;import lsbpm.db.domain2.TCategory;import lsbpm.db.domain2.TDoc;import lsbpm.db.domain2.TDocCategory;import lsbpm.db.domain2.TStaff;import lsbpm.web.lecene.LuceneIndex;import net.sf.json.JSONObject;import org.apache.struts2.ServletActionContext;/** * Show case File Upload example's action. FileUploadAction */public class FileUploadAction extends BaseAction {private static final long serialVersionUID = 5156288255337069381L;private String contentType;private File upload;private String fileName;private String caption;    private String CId;//文档TCategory的IDprivate String jsonMsg;// 返回ExtJs upload form消息    private String Tab_staffId;public String getJsonMsg() {return jsonMsg;}public void setJsonMsg(String jsonMsg) {this.jsonMsg = jsonMsg;}// since we are using the file name will be// obtained through getter/setter of FileNamepublic String getUploadFileName() {return fileName;}public void setUploadFileName(String fileName) {this.fileName = fileName;}// since we are using the content type will be// obtained through getter/setter of ContentTypepublic String getUploadContentType() {return contentType;}public void setUploadContentType(String contentType) {this.contentType = contentType;}// since we are using the File itself will be// obtained through getter/setter of public File getUpload() {return upload;}public void setUpload(File upload) {this.upload = upload;}public String getCaption() {return caption;}public void setCaption(String caption) {this.caption = caption;}// 解析上传的流程文件,将流程图分解后存入数据库中// 用json格式返回成功失败及错误信息等,可直接与ExtJS衔接。public String combinStr(String str,int i){str=str.substring(0,str.indexOf("."))+i+ str.substring(str.indexOf("."));return str;}public String upload() throws Exception {System.out.println("执行上传文件操作。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。");// 定义要返回的对象,返回时用json包装HashMap retMsg = new HashMap();TStaff staff=(TStaff)genericService.findById(TStaff.class, Tab_staffId);TCategory category=(TCategory)genericService.findById(TCategory.class, CId);TDoc doc = new TDoc();doc.setName(fileName);//-------------------------------------------------(1)filename属性(非空)System.out.println("拼装前------------------>"+fileName);List propertisList=new ArrayList();propertisList.add("docVersion-");  List result=genericService.findByProperty(doc, propertisList, 0, 0);doc.setDocVersion(1);//-------------------------------------------------(2)DocVersion属性(非空)        int size=propertisList==null?0:result.size();        if(size>0){       int docVersion=result.get(0).getDocVersion();       doc.setDocVersion(docVersion+1);       fileName=combinStr(fileName,docVersion+1);主要针对相同名称的文件处理加上版本号       System.out.println("--------------------经过版本升级---------------------------------");        }        doc.setDocAlias(fileName);//-------------------------------------------------(3)DocAlias属性(非空)        doc.setBoost(0d);//-------------------------------------------------(4)Broost属性(非空)        System.out.println("拼装后----------------->"+fileName);       String realPath="E:\\DataDir\\"+fileName;if (upload.isFile()) {BufferedInputStream bis = new BufferedInputStream(new FileInputStream(upload));BufferedOutputStream bos = null;try {bos = new BufferedOutputStream(new FileOutputStream(realPath));//为以防万一,以后写文件的路径尽量写成正双斜杠的// 从源文件中取数据,写到目标文件中byte[] buff = new byte[8192];for (int len = -1; (len = bis.read(buff)) != -1;) {bos.write(buff, 0, len);}bos.flush();} catch (IOException ie) {ie.printStackTrace();} finally {if (bis != null) {try {bis.close();} catch (IOException ie) {ie.printStackTrace();}}if (bos != null) {try {bos.close();} catch (IOException ie) {ie.printStackTrace();}}}       System.out.println("----------------------------0000");doc.setDocUrl(fileName);//-------------------------------------------------(5)DocUrl属性(非空)    doc.setExtType(fileName.substring(fileName.lastIndexOf('.')+1));//---------(6)extType属性(非空)   doc.setState("可用");//状态这个暂时写死为可用 //----------------------------------(7)state属性(非空)doc.setTStaffByDesigner(staff);//设计者先和操作者暂定为同一人-------------------- (8)designer属性(可空)    doc.setTStaffByOperator(staff);//------------------------------------------(9)operator属性(非空)    doc.setUpgradeDate(new Timestamp(System.currentTimeMillis()));boolean isSuccess = false;System.out.println("即将要插入数据库的文件内容为:"+doc);genericService.create(doc);//插入文档类型TDocCategory cate=new TDocCategory();cate.setTCategory(category);cate.setTDoc(doc);cate.setBoost(0d);genericService.create(cate);String Id = doc.getDocId();System.out.println("新增后获取到的员工ID" + Id);System.out.println(fileName + "----------------");String extTypes=doc.getExtType();//如果上传的文件在我要建立索引的范围之内,可以见索引,否则不建立if(extTypes.equals("pdf")||extTypes.equals("html")||extTypes.equals("rtf")||extTypes.equals("doc")||extTypes.equals("ppt")||extTypes.equals("xls")||extTypes.equals("txt")){ LuceneIndex index=new LuceneIndex();//建立索引     index.buildsingle(doc);     System.out.println("索引完毕。。。。。。。。。。。。。。。。。。。。。");}   // 流程文件解析和加载,成功! 将流打到客户端retMsg.put("success", "true");retMsg.put("docId", Id);retMsg.put("name", doc.getDocAlias());if(doc.getTDocCategories().size()==1){ for(TDocCategory cate1:doc.getTDocCategories()){ retMsg.put("CName",cate1.getTCategory().getName()); }}retMsg.put("extType", doc.getExtType());retMsg.put("state", doc.getState());retMsg.put("docId", doc.getDocId());retMsg.put("docUrl", doc.getDocUrl());retMsg.put("upload", "ok");retMsg.put("msg", "hhaahhaa!!");} else {// 流程文件解析和加载,失败!retMsg.put("failure", "true");retMsg.put("upload", "error");retMsg.put("msg", " failed !!");}// json包装返回对象jsonMsg = JSONObject.fromObject(retMsg).toString();return SUCCESS;}public String getFileName() {return fileName;}public void setFileName(String fileName) {this.fileName = fileName;}public String getCId() {return CId;}public void setCId(String cId) {CId = cId;}public String getTab_staffId() {return Tab_staffId;}public void setTab_staffId(String tabStaffId) {Tab_staffId = tabStaffId;}}

struts.xml中添加一行代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值