总所周知,Javascript代码是无法直接访问本地文件的,因此,做到真正的可预览还是比较麻烦的,这里我只是做了个表面上开起来像是可预览图片的一个小程序.
申明:EXTJS上传照片是会出现刷新的,但是在页面上感觉不出来已经被刷新过,因为其内部还是创建了一个iframe作为上传的临时页面的,它刷新的只是这个临时的iframe而已.
//==================第一步,copy官方Demo上的js代码(名字为 FielUploadField.js)=======================
Ext.form.FileUploadField = Ext.extend(Ext.form.TextField,
});
Ext.reg('fileuploadfield', Ext.form.FileUploadField);
//===================第二步,继续copy官方Demo上的CSS样式表文件(是否必须我没测试,文件名随意)=======================
.x-form-file-wrap {
}
.x-form-file-wrap .x-form-file {
position: absolute;
right: 0;
-moz-opacity: 0;
filter:alpha(opacity: 0);
opacity: 0;
z-index: 2;
}
.x-form-file-wrap .x-form-file-btn {
position: absolute;
right: 0;
z-index: 1;
}
.x-form-file-wrap .x-form-file-text {
}
//====================第三步,编写我们自己的JS==========================
var photoName=null;//后面要用到这个
var formPanel=new Ext.FormPanel({
//非关键性代码略去
items:[{
html:"<img id="p" src="../empPhoto/default.png"; height="180";>"//先放一个默认图片
}]
})
//===================第四步,创建上传组件=============================
var upload = new Ext.form.FileUploadField({
id : 'form-file',
fieldLabel : '照片',
name : 'ff',//就是后台要获取的name
buttonCfg : {
text : '',
iconCls : 'pluginIcon'
},
listeners : {
//此事件请参考FileUploadField.js里面的代码
'fileselected' : function() {
var x = upload.getValue();
if (!x || !y)
return;
var patn = /\.jpg$|\.jpeg$|\.gif$|\.png&/i;//判断文件后缀名
if (!patn.test(x)) {
alert("您选择的不是图像文件!");
}
}
}
});
//创建一个FormPanel
var fp = new Ext.FormPanel({
fileUpload : true,
frame : true,
baseCls : 'x-plain',
layout : 'form',
labelWidth : 50,
defaults : {
anchor : '95%',
allowBlank : false
},
items : [upload]//把上面的对象加入到此FormPanel里
});
var addPhotoWin;//创建一个window用于显示上面的FormPanel,因为在IE和火狐中,是不允许出现嵌套form表单的(Google浏览器可以...汗一个)
var btn = Ext.get('addPhoto');
btn.on('click', function() {
if (!addPhotoWin) {
addPhotoWin = new Ext.Window({
frame : true,
layout : 'fit',
width : 300,
modal : true,
height : 130,
title : '上传照片',
defaults : {
style : "padding:10px;"
},
resizable : false,
closeAction : 'hide',
items : [fp],
buttons : [{
text : '保存',
id : 'save',
handler : function() {
if (fp.getForm().isValid()) {
//这里正常提交表单,就跟普通表单一样.
fp.getForm().submit({
url : 'basicEmployees.do?method=addPhoto',
method : 'POST',
waitMsg : '正在上传照片...',
success : function(fp, o) {
//接收后台返回的数据,暂时看不懂就先不用看,看完后台代码后就什么都知道了
photoName = o.result.data;//将后台返回上来的文件名赋值给它,以后就可以通过它来提交到数据库了.数据库中只要保存图片名称即可
var dom = document.getElementByIdx('p');//获得刚才Panel里面的html的id为p的dom对象
dom.src = "../empPhoto/" + photoName
+ "";//修改dom对象的属性,因为id为p的dom对象是个img,所以可以直接点他的src修改他图片路径
}
});
}
}
}, {
text : '重置',
handler : function() {
fp.getForm().reset();
}
}]
});
};
addPhotoWin.show();
});
//===================至此,前台搞定====================
//===================后台开始=======================/
//Struts的上传应该大家都很熟悉了,很简单的一个东西.就是先在form中加入一个FormFile(这玩意儿是个接口....)属性,并且提供get,set方法
//import org.apache.struts.upload.FormFile;
private FormFile ff;
public FormFile getFf() {
return ff;
}
public void setFf(FormFile ff) {
this.ff = ff;
}
//=======================Action中的代码(DispatchAction)====================
public ActionForward addPhoto(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException {
BasicEmployeesForm basicEmployeesForm=(BasicEmployeesForm)form;//
FormFile ff = basicEmployeesForm.getFf();//实例化FormFile
if (ff != null) {
System.out.println(ff.getFileName());
String name = ff.getFileName();//获得文件名
int index = name.lastIndexOf(".");
String type = name.substring(index, name.length());//获得文件后缀
String uuid = UUID.randomUUID().toString();//通过uuid生成一个唯一字符串,目的是保证此文件的唯一性
String savePath = request.getSession().getServletContext()
.getRealPath("/");//获得系统运行路径
System.out.println(savePath);
FileOutputStream fps = new FileOutputStream(savePath + "empPhoto\\"
+ uuid + type);//文件流路径,这里的文件名修改成了uuid+type,例如8s5d1-4785-8d5a2-7a8x52-7a41s.png
fps.write(ff.getFileData());//写入文件
fps.flush();//搽干净屁股
fps.close();//关闭文件流
response.getWriter().write(
"{success:true,data:'" + uuid + type + "'}");//返回已经上传到服务器的文件的文件名,在前台获取此文件名之后就可以根据此文件名修改那个默认头像<img>便签的src路径了
} else {
response.getWriter().write("{success:false}");
}
return null;
}
//=====================可能写的有点乱,不足之处大家多包含.....由于项目还在开发中...没法把半成品打包上载....不好意思,无法提供源码下载====================