论坛首页 Web前端技术论坛

extJs之简易上传控件

浏览 13652 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (2) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-07-21  

  ext的官方网站有许多大侠写了许多狠牛的上传控件,但是功能太炫,我感觉反而不适用!效果如下 上传完了之后地址会加载到上传内容这个文本框里面 里面还做了类型判断,用于上传文本和相片代码如下,把一下代码封装在一个js文件里面

//*****************************************上传的公共js***************************************************************//

/**

 * 约定:types为调用时传来的参数.形式为jsp-gig-png

 *      uploadid为上传后要填充路径的控件id

 *      上传的属性均为upload

 * 功能:页面调用openUpload("","");方法即可

 */

//...允许上传的后缀名

var types = "";



//...上传后填充控件的id

var uploadid = "";



function openUpload(type,id){

  	types = type;

	uploadid = id;

  	winUpload.show();

  }



var formUpload = new Ext.form.FormPanel({

    baseCls: 'x-plain',

    labelWidth: 80,

    fileUpload:true,

    defaultType: 'textfield',

    items: [{

      xtype: 'textfield',

      fieldLabel: '文 件',

      name: 'upload',

      inputType: 'file',

      allowBlank: false,

      blankText: '请上传文件',

      anchor: '90%'  // anchor width by percentage

    }]

  });



var winUpload = new Ext.Window({

    title: '资源上传',

    width: 400,

    height:200,

    minWidth: 300,

    minHeight: 100,

    layout: 'fit',

    plain:true,

    bodyStyle:'padding:5px;',

    buttonAlign:'center',

    items: formUpload,

    buttons: [{

      text: '上 传',

      handler: function() {

        if(formUpload.form.isValid()){

          Ext.MessageBox.show({

               title: 'Please wait',

               msg: 'Uploading...',

               progressText: '',

               width:300,

               progress:true,

               closable:false,

               animEl: 'loding'

             });

          formUpload.getForm().submit({    

		    url:'uploadAction.action?types='+types,

            success: function(form, action){

			   var objxzdz = Ext.get(uploadid).dom;

			   var value = action.result.msg;

			   objxzdz.value = value;

               Ext.Msg.alert('成功','上传成功.');

               winUpload.hide();  

            },    

             failure: function(form, action){    

			  //... action生成的json{msg:上传失败},页面就可以用action.result.msg得到非常之灵活

              Ext.Msg.alert('Error', action.result.msg);    

             }

          })           

        }

       }

    },{

      text: '取 消',

      handler:function(){winUpload.hide();}

    }]

  });

//*****************************************上传的公共js***************************************************************//

现在已经封装完毕了,我们看看在页面上如何调用
openUpload("txt-xls-doc-docs-pds","xzdzid");
就这一句话,嘿嘿,简单吧?第一个参数为允许上传的类型,第二个参数为上传后地址要绑定到哪个控件(是该控件的id)

action的代码还是贴下吧
import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;



import org.apache.struts2.ServletActionContext;



import net.ask123.ecommerce.common.util.Common;

import net.ask123.ecommerce.common.util.Constants;

import net.ask123.ecommerce.common.util.FileOperate;

import net.ask123.ecommerce.common.util.VeDate;



/**

 * 上传的公共方法

 * 

 * @author sam.zhang

 * 

 */

public class UploadAction extends ExtJsonActionSuport {



	/**

	 * 

	 */

	private static final long serialVersionUID = 1L;


        //和前台的名字一样,这里约定是 upload
        private File upload;



	private String uploadContentType;



	private String uploadFileName;



	private String savePath;



	// 存放允许上传的后缀名

	private String types;



	public String getSavePath() {

		return savePath;

	}



	public void setSavePath(String savePath) {

		this.savePath = savePath;

	}



	public File getUpload() {

		return upload;

	}



	public void setUpload(File upload) {

		this.upload = upload;

	}



	public String getUploadContentType() {

		return uploadContentType;

	}



	public void setUploadContentType(String uploadContentType) {

		this.uploadContentType = uploadContentType;

	}



	public String getUploadFileName() {

		return uploadFileName;

	}



	public void setUploadFileName(String uploadFileName) {

		this.uploadFileName = uploadFileName;

	}



	public String getTypes() {

		return types;

	}



	public void setTypes(String types) {

		this.types = types;

	}



	@SuppressWarnings("deprecation")

	public String execute() throws Exception {

		String msg = "";

		FileOperate fo = new FileOperate();



		String sid = VeDate.getNo(4);



		this.savePath = "/updownFiles";



		try {



			// ...获取文件后缀名

			String ext = fo.getFileExt(getUploadFileName());



			if ("".equals(this.types)

					|| Common.indexofString(this.types, "-") == -1) {

				msg = "上传失败";

				this.setJsonString("{success:false,msg:'" + msg + "'}");

				return SUCCESS;

			}



			// ...判断上传的文件是否合法

			boolean istrue = FileOperate.trueExt(this.types.split("-"), ext);

			if (!istrue) {

				msg = "您上传的文件格式不正确,正确格式为" + this.types;

				this.setJsonString("{success:false,msg:'" + msg + "'}");

				return SUCCESS;

			}



			// ...文件存放的位置

			String sPath = ServletActionContext.getRequest().getRealPath(

					this.getSavePath())

					+ Constants.FILESPARA

					+ sid.substring(0, 4)

					+ Constants.FILESPARA

					+ sid.substring(4, 6)

					+ Constants.FILESPARA;



			// ...保存在数据库的路径

			String filePath = this.savePath + "/" + sid.substring(0, 4) + "/"

					+ sid.substring(4, 6) + "/" + sid + "." + ext;



			// 如果目录不存在则创建它



			fo.createFolder(sPath);



			FileOutputStream fileOutputStream = new FileOutputStream(sPath

					+ sid + "." + ext);



			FileInputStream fileInputStream = new FileInputStream(getUpload());

			// ...

			byte[] buffer = new byte[1024];

			int len = 0;

			while ((len = fileInputStream.read(buffer)) > 0) {

				fileOutputStream.write(buffer, 0, len);

			}

			this.setJsonString("{success:true,msg:'" + filePath + "'}");

		} catch (Exception e) {

			this.setJsonString("{success:false}");

			e.printStackTrace();

		}

		return SUCCESS;

	}



}

这里就大致贴贴一下吧,如果看不懂的话把struts2学习下就ok了,这里不一定后台一定是java的,

关键是

url:'uploadAction.action?types='+types,这里会指定后台的请求地址
   发表时间:2008-07-22  
不错,有点问题想问问
客户端的文件上传类型设了有什么用?
0 请登录后投票
   发表时间:2008-07-23  
只是做个验证
如果上传图片你传个txt文件的话struts2会返回一个json提示你类型不匹配
  其实这点不是狠好,还是经过了服务器,希望大家可以提意见改进
  还有,我博客都是从csdn搬过来的,可能有些地方有问题,大家都提出来
0 请登录后投票
   发表时间:2008-09-13  
请教下,上传完后的那个图片存放的地址是如何放到前台的输入框里边的,呵呵,不知道有没有完整的例子参考下,谢谢了。
0 请登录后投票
   发表时间:2008-09-15  
为什么我按照楼主的做了但是前台总是提示:action.result is undefined

这个是什么原因呢?
0 请登录后投票
   发表时间:2008-09-17  
应该不会的
  wwwtd好好检查一下
  还有什么问题的话把邮箱发给我
  我传个例子你
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics