在我们开发WEB项目时,文件上传是最常用的功能,我最近在做一个自定义表单的 项目,当然自定义表单可能包含的控件包括普通文本,数字,日期,多行文本,富文本编辑,文件上传等控件,我是这样实现这个文件上传的控件,其中上传使用 common-upload开源包,上传完毕后用同样名称的隐藏字段替换原先的文件上传框,这样可实现表中字段与隐藏字段对应(此时是一个相对地址),后 台代码如下:
Java代码- String path = request.getContextPath();
- String name = StrCharUtil.formatNullStr(request.getParameter("name"));
- Date date = new Date();
- String classpath = FromAction.class.getResource("/")
- .getPath().replaceAll("WEB-INF/classes/",
- "upload/");
- FileUtil.mkDir(classpath
- + DateFormatUtil.SIMPLE_DATE_FORMAT_yyyy
- .format(date));
- FileUtil.mkDir(classpath
- + DateFormatUtil.SIMPLE_DATE_FORMAT_MM
- .format(date));
- FileUtil.mkDir(classpath
- + DateFormatUtil.SIMPLE_DATE_FORMAT_dd
- .format(date));
- String savePath = classpath ;
- SingleFileUpload upload = new SingleFileUpload();
- upload.parseRequest(request);
- File parent = new File(savePath);
- String ret = upload.upload(parent);
- String downloadPath = ret.substring(ret.indexOf("upload")+6,ret.length());
- String fileName = FileUtil.getFilename(ret);
- out.println("<input type=\"hidden\" name=\""+name+"\" value=\""+downloadPath+"\"/>文件<a href=\""+path+"/upload/"+downloadPath+"\">"+fileName+"</a>已上传到服务器");
前台控件如下(初始化所有样式为eform_uploadfile的文件上传框):
Js代码- var myName = $(".eform_uploadfile").attr("name");
- var myUpload = $(".eform_uploadfile").upload({
- name: 'file',
- action: '/eForm/upload.jsp?name='+myName,
- enctype: 'multipart/form-data',
- params: {},
- autoSubmit: true,
- onSubmit: function() {},
- onComplete: function(response) {$(".eform_uploadfile").replaceWith(response);},
- onSelect: function() {}
- });