struts2+extjs文件上传完整实现(解决了上传中的各种问题)

首先需要引入上传控件

<script type="text/javascript" src="<%=basePath%>/js/ext/examples/ux/fileuploadfield/FileUploadField.js" charset="utf-8"></script>

弹出上传框对应extjs代码

var uploadForm=new Ext.FormPanel({
	id:'uploadForm',
	width:520,
	frame:true,
	fileUpload: true,
	autoHeight:true,
	bodyStyle:'10px 10px 0px 10px',
	labelWidth:50,
	enctype: 'multipart/form-data',
	defaults:{
		anchor: '95%',
        allowBlank: false
	},
	items:[
		{
			xtype:'fileuploadfield',
			emptyText: '请选择上传文件...',
            fieldLabel: '文件:',
            id:'uploadFile',
            name: 'upload',
            allowBlank: false,
            blankText: '文件名称不能为空.',
             buttonCfg: {
	    				text: '选择...'// 上传文件时的本地查找按钮
	          }
		}
	],
	buttons: [{
	                text: '上传',
	                handler: function(){
	                    if(uploadForm.getForm().isValid()){
	                    	uploadForm.getForm().submit({
	    	                    url:basePath+ '/documentManage/upload_upload.action',
	    	                    method:'POST',
	    					    waitTitle: '请稍后',
	    	                    waitMsg: '正在上传文档文件 ...',
	    						success: function(fp, action){
	    	                	  	Ext.MessageBox.alert('信息', action.result.msg);
	    	                        Ext.getCmp("uploadFile").reset();          // 指定文件字段的id清空其内容
	    	                        addwin.hide();
									grid.store.load({params:{start : 0,limit : combo.value}});
	    	                    },
	    						failure: function(fp, action){
	    	                        Ext.MessageBox.alert('警告', action.result.msg);
	    	                        addwin.hide();
	    	                    }
	     	                });
	                    }
	                }
	            },{
	                text: '重置',
	                handler: function(){
	            		uploadForm.getForm().reset();
	                }
	            }]

});

addwin = new Ext.Window({
	title : '上传新文档',
	closable : true,
	width : 520,
	autoHeight: true,
	border : false,
	plain : true,
	modal : true,
	layout : 'fit',
	bodyStyle : 'padding:5px;',
	maximizable : false,// 禁止最大化
	closeAction : 'hide',
	closable : true,// 是否有关闭
	collapsible : true,// 可折叠
	iconCls : 'bind',
	items : [uploadForm]
});

struts2 action代码

package cn.com.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 javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import cn.com.css.common.action.BaseAction;

public class FileUploadAction extends BaseAction {

	private static final long serialVersionUID = 5156288255337069381L;

	private  String msg;
	private String contentType;
	private File docmentFile;
	private String fileName;

	public String upload() throws Exception {
		String realPath = "E:\\" + fileName;
		if (docmentFile.isFile()) {
			BufferedInputStream bis = new BufferedInputStream(
					new FileInputStream(docmentFile));
			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();
				msg="文件上传失败";
				HttpServletResponse response = ServletActionContext.getResponse();
				response.setContentType("text/html;charset=UTF-8");
				return "none";
			} finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException ie) {
						ie.printStackTrace();
					}
				}
				if (bos != null) {
					try {
						bos.close();
					} catch (IOException ie) {
						ie.printStackTrace();
					}
				}
			}
		}
		msg="文件上传成功";
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		return "none";
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	// since we are using <s:file name="upload" .../> the file name will be
	// obtained through getter/setter of <file-tag-name>FileName
	public String getUploadFileName() {
		return fileName;
	}

	public void setUploadFileName(String fileName) {
		this.fileName = fileName;
	}

	// since we are using <s:file name="upload" ... /> the content type will be
	// obtained through getter/setter of <file-tag-name>ContentType
	public String getUploadContentType() {
		return contentType;
	}

	public void setUploadContentType(String contentType) {
		this.contentType = contentType;
	}

	// since we are using <s:file name="upload" ... /> the File itself will be
	// obtained through getter/setter of <file-tag-name>
	public File getUpload() {
		return docmentFile;
	}

	public void setUpload(File docmentFile) {
		this.docmentFile = docmentFile;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public File getDocmentFile() {
		return docmentFile;
	}

	public void setDocmentFile(File docmentFile) {
		this.docmentFile = docmentFile;
	}

}

struts.xml配置:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="documentManage" namespace="/documentManage"
		extends="global-struts-default">

		<action name="upload_*"
			class="cn.com.FileUploadAction"
			method="{1}">
			<result type="json" name="none">
				<param name="contentType">text/html;charset=utf-8</param>
				<param name="excludeProperties">
				    user.myQuestionses,user.messages,user.myNotes,user.taskPapers,
				    user.tasks,user.testPapers,user.articles
  				</param>
			</result>
		</action>
	</package>
</struts>

struts2+extjs文件上传完整实现(解决了上传中的各种问题)

时间: 2024-11-07 20:08:32

struts2+extjs文件上传完整实现(解决了上传中的各种问题)的相关文章

Unity3d导出Android的apk文件时相关问题的解决办法

[狗刨学习网] 今天上午着手将一个unity3d开发的小游戏build到android手机上运行,结果遇到了不少问题. 首先遇到的第一个问题是在build到一半的时候,弹出如下报错: Error building Player: UnityException: No platforms found Android SDK does not include any platforms! Did you run Android SDK setup to install the platform(s)

Struts2 + uploadify 多文件上传完整实例!

首先我这里使用的是  Jquery  Uploadify3.2的版本  导入相关的CSS  JS    <link rel="stylesheet" type="text/css" href="<%=basePath%>css/uploadify/uploadify.css"> <script src="<%=basePath%>js/jquery.min.js"></sc

Struts2 + uploadify 多文件上传完整的例子!

首先,我这里使用的是  Jquery  Uploadify3.2版本号  导入相关的CSS  JS    <link rel="stylesheet" type="text/css" href="<%=basePath%>css/uploadify/uploadify.css"> <script src="<%=basePath%>js/jquery.min.js"></s

Struts2单文件上传原理及示例

一.文件上传的原理 表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值: 1.application/x-www-form-urlencoded:这是默认编码方式,它只处理表单域里的value属性值,采用这种编码方式的表单会将表单域的值处理成URL编码方式. 2.multipart/form-data:这种编码方式的表单会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数里. 3.text/plain:这种方式主要适用于直接通过表单发送邮件的

Struts2控制文件的上传与下载

Struts2控制文件上传与下载的几个注意事项: (1)必须将表单的method设置为post,将enctype设置为multipart/from-data.只有这样,浏览器才会把用户选择文件的二进制数据发送给数据. (2)Struts2默认使用的是Jakarta的Common-FileUpload的文件上传框架,因此,如果需要使用Struts2的文件上传功能,则需要在web应用中增加两个JAR文件,即commons-io-2.2.jar和commons-fileupload-1.3.1.jar

Extjs文件上传问题总结

本来文件上传是一个简单而常用的功能,但是,由于刚刚接触extjs,对extjs中的控件及其使用方法并不熟悉,导致本来一个很快就可以搞定的文件上传问题,弄了将近两天的时间.现将问题及解决办法发出来,供有相同烦恼的博园参考.只是我第一次发文,如有不妥,望各位海涵. 问题描述:在文件上传的时候,在ie浏览器下,文件上传成功以后返回response时,回调函数直接报错:无法调用null或者空值的success属性. 首先看下extjs的代码: <html xmlns="http://www.w3.

Struts2实现文件上传报错(四)

1.具体错误如下 2014-5-2 21:38:29 com.opensymphony.xwork2.util.logging.jdk.JdkLogger error 严重: Exception occurred during processing request: null java.lang.NullPointerException at com.you.file.upload.action.FileUploadAction.execute(FileUploadAction.java:56)

Struts2实现文件上传报错(一)

1.具体报错如下 2014-5-1 23:02:38 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet [jsp] in context with path [/UploadFile] threw exception [An exception occurred processing JSP page /file.jsp at line 28 25: <table> 26

Struts2实现文件上传报错(三)

1.具体错误如下 usage: java org.apache.catalina.startup.Catalina [ -config {pathname} ] [ -nonaming ] { -help | start | stop } 2014-5-1 23:17:23 org.apache.catalina.core.AprLifecycleListener init 信息: Loaded APR based Apache Tomcat Native library 1.1.27 usin