论坛首页 AJAX版 EXT

ext2.0在提交form表单时上传文件的问题

浏览 2349 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
时间:2007-11-12
普通表单提交是没有问题,当需要上传文件时,设置fileUpload:true之后提交会报一个语法错误,位置是JSON.js中的
    
this.decode = function(json){
        return eval("(" + json + ')');
};

这时json竟然是字符串 “<PRE></PRE>”!
服务器端用的是struts2.0,方法中根本没有向返回的流中写任何东西。
我发现问题出自Connection.js中的doFormUpload方法,这个方法专门出来带上传文件的表单提交,首先在文档中创建一个iframe,然后把form向这个iframe里提交,经过一系列复杂的方法调用,最后调用了Action.js中的handleResponse 方法:
 
handleResponse : function(response){
        if(this.form.errorReader){
            var rs = this.form.errorReader.read(response);
            var errors = [];
            if(rs.records){
                for(var i = 0, len = rs.records.length; i < len; i++) {
                    var r = rs.records[i];
                    errors[i] = r.data;
                }
            }
            if(errors.length < 1){
                errors = null;
            }
            return {
                success : rs.success,
                errors : errors
            };
        }
        return Ext.decode(response.responseText);
}

我没有定义form.errorReader,最后调用的decode方法,报错。
有几个不解的地方:
1、为何responseText是<PRE></PRE>
2、decode方法起到了什么作用,这里为何要调用decode方法
3、普通表单的提交为何并没有这样的问题
   
时间:2007-11-12
我是修改ext的代码,把
过滤掉就好了。
   
0 请登录后投票
时间:2007-11-13
上传文件的头还是html 而不是plain
   
0 请登录后投票
时间:2008-01-23
这个非常的简单,getResponse().setContentType("application/json"); 就可以了
   
0 请登录后投票
时间:2008-04-16
edgeloner 写道
我是修改ext的代码,把
过滤掉就好了。


怎么过滤掉啊,能不能说的更清楚一点。

   
0 请登录后投票
时间:2008-05-13
我用ext2.0+struts2来做文件上传,服务器返回的json数据客户端总提示我下载文件,不知道怎么回事:
代码如下:
<div>
<div id="fileUpload"></div>
</div>
<script type="text/javascript">
Ext.onReady(function(){
var uploadFile = function(){
if (form.form.isValid()){
form.getForm().submit({
waitMsg : '正在登录......',
failure: function(form,action){
Ext.MessageBox.hide();
Ext.MessageBox.alert('Error',action.result.msg);
},
success: function(form,action){
Ext.MessageBox.hide();
alert(action.response);
for(key in action.response){
alert(key+'==='+action.response[key]);
}
Ext.MessageBox.alert('Success',action.result.msg);
},
method : 'POST'
});
}
}
var form = new Ext.form.FormPanel({
labelAlign: 'right',
title: 'form',
labelWidth: 50,
frame:true,
fileUpload: true,
url: '../test/uploadFile.action',//fileUploadServlet
width: 380,
items: [{
xtype: 'textfield',
fieldLabel: '文本框',
name: 'upload',
inputType: 'file'//文件类型
}],
buttons: [{
text: '按钮',
handler: uploadFile
}]
});
form.render("fileUpload");
});
</script>
   
0 请登录后投票
时间:2008-05-13
Fangrn 写道
我用ext2.0+struts2来做文件上传,服务器返回的json数据客户端总提示我下载文件,不知道怎么回事:
代码如下:
<div>
<div id="fileUpload"></div>
</div>
<script type="text/javascript">
Ext.onReady(function(){
var uploadFile = function(){
if (form.form.isValid()){
form.getForm().submit({
waitMsg : '正在登录......',
failure: function(form,action){
Ext.MessageBox.hide();
Ext.MessageBox.alert('Error',action.result.msg);
},
success: function(form,action){
Ext.MessageBox.hide();
alert(action.response);
for(key in action.response){
alert(key+'==='+action.response[key]);
}
Ext.MessageBox.alert('Success',action.result.msg);
},
method : 'POST'
});
}
}
var form = new Ext.form.FormPanel({
labelAlign: 'right',
title: 'form',
labelWidth: 50,
frame:true,
fileUpload: true,
url: '../test/uploadFile.action',//fileUploadServlet
width: 380,
items: [{
xtype: 'textfield',
fieldLabel: '文本框',
name: 'upload',
inputType: 'file'//文件类型
}],
buttons: [{
text: '按钮',
handler: uploadFile
}]
});
form.render("fileUpload");
});
</script>


关注下!
我也是这样,返回数据也是符合格式的,使用的是jsonplugin.
   
0 请登录后投票
时间:2008-05-19
rsponse.setContentType("text/html")
   
0 请登录后投票
时间:2008-06-27
嘿嘿,这个问题开始我也遇到了,也看到这个帖子,也试过response.setContentType("text/html"),不好用,当时也没仔细想.

今天又有个人问我,呵呵,我研究了一下

只要在struts2的输出中配置<param name="contentType">text/html</param>就行了,在response中配的话,最后都会被默认的contentType改写的
   
0 请登录后投票
时间:2008-06-30
经过几天努力,终算成功了!

不过郁闷,参数居然不起作用。迷惑郁闷中。。。

解决之道:在url中加入参数。
如 url:login.do?aa=bb&aa1=cc

------------------------------
服务器是spring (这个影响不到)

上传组件,用到了apacher的fileLoad
关键处:
1 (1) 服务器返回数据类型应设为text/html.
Response. setContentType("text/html; charset=utf-8");
(2) 返回字符串格式应有:
success部分,其后为false或true;
msg部份,其后是要返回的信息。
例1:服务器返回成功信息
{success:true,msg:'成功'}
例2:服务器返回失败信息
{success:false,msg:'失败'}

2 客户端
(1) Formpanel的fileUpload属性其值要设成true
(2) 表单提交回调的两个函数应为:
failure: function(form,action){},
success: function(form,action){}


客户端源码
ddd.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="resources/ext21/resources/css/ext-all.css" /> 
        <link rel="stylesheet" type="text/css" href="resources/ext21/resources/css/fyhC.css" /> 
        <script type="text/javascript" src="resources/ext21/adapter/ext/ext-base.js"></script>
        <script type="text/javascript" src="resources/fckeditor/fckeditor.js"></script>
        <script type="text/javascript" src="resources/ext21/ext-all.js"></script>
    </head>
<script>   
    
    Ext.onReady( function (){
        var form = new Ext.form.FormPanel({ 
            labelAlign: 'right', 
            title: 'form', 
            labelWidth: 50, 
            frame:true, 
            fileUpload: true, 
            baseParams : {aa:'bb'},   //文件上传时,没有用?迷惑中
            url:" login.do",
            width: 380, 

            items: [{ 
                xtype: 'textfield', 
                fieldLabel: '文本框', 
                name: 'file', 
                inputType: 'file'//文件类型 
            }], 
            buttons: [{ 
                text: '按钮', 
                handler: s
            }] 
        }); 
        function s() {
            form.getForm().submit({//客户端的数据提交给服务器
                waitTitle:"请稍候",
                waitMsg:"正在提交表单数据,请稍候。。。。。。", 
                //如果submit失敗,執行這一個function   
                failure:function(form1,action){         
                    Ext.MessageBox.hide(); 
                    Ext.MessageBox.alert('Error',action.result.msg);
                },   
                success: function(form1,action){   
                    Ext.MessageBox.hide();   
                    Ext.MessageBox.alert('Success',action.result.msg);   
                 }                   
             })
        }

        form.render(document.body);  
        
    });
    
</script>        
    <body>
        <div id="hello"/>
    </body>
</html>



服务端源码
login.java
 

package action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
 
/**
 *
 * @author cloud
 */
public class Login  extends SimpleFormController{
    public  Login(){
//        this.setCommandClass(Fuser.class);
    }
    
    private static final long serialVersionUID = 7440302204266787092L;
    String uploadPath = "d:\\uploadtest\\"; // 用于存放上传文件的目录
    String tempPath = "d:\\tmp\\"; // 用于存放临时文件的目录

    @Override
    protected ModelAndView onSubmit(HttpServletRequest arg0, HttpServletResponse arg1, Object cmd, BindException ex) throws Exception {
       arg1.setContentType("text/html; charset=utf-8");
      // arg1.setContentType("text/html; charset=ISO-8859-4"); 

       ModelAndView aaa=null;
       String data="{success:flase,msg:'失败'}";
         
//       if ( !( arg0.getParameter("aa").equals("bb") )  ) {
//            aaa=new ModelAndView(this.getFormView());
//             arg1.getWriter().print("{success:flase,message:'失败1'}");
//            return aaa;  
//        }
       try {
            java.io.File tmpfile=new java.io.File(tempPath);
            boolean isMultipart = ServletFileUpload.isMultipartContent(arg0);
            DiskFileItemFactory  factory = new DiskFileItemFactory();
            factory.setSizeThreshold(4096);//设置缓冲区大小,这里是4kb
            factory.setRepository(tmpfile); // 设置临时目录
            
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(4194304);// 设置最大文件尺寸,这里是4MB

            List  fileItems = upload.parseRequest(arg0);// 得到所有的文件:
            Iterator i = fileItems.iterator();
            // 依次处理每一个文件:
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                String fileName = fi.getName();// 获得文件名,这个文件名包括路径:
                if (fileName != null) {
                    // 在这里可以记录用户和文件信息
                    // 此处应该定义一个接口(CallBack),用于处理后事。
                    // 写入文件a.txt,你也可以从fileName中提取文件名:
                    String extfile = fileName.substring(fileName.indexOf("."));
                    Timestamp now = new Timestamp((new java.util.Date())
                         .getTime());
                    SimpleDateFormat fmt = new SimpleDateFormat(
                         "yyyyMMddHHmmssSSS");
                    String pfileName = fmt.format(now).toString().trim();
                    System.out.println(uploadPath + pfileName + extfile);
                    fi.write(new File(uploadPath + pfileName + extfile));
                 
                }
            }
            
            data="{success:true,msg:'上传成功'}";
        } catch (Exception e) {
            data="{success:flase,msg:'失败'}";
            // 可以跳转出错页面
           // aaa=new ModelAndView(this.getFormView());
        } finally{
             arg1.getWriter().write(data);
             arg1.getWriter().flush();

             return aaa;
        }  
    }
     
   

}

   
0 请登录后投票
论坛首页 AJAX版 EXT

跳转论坛: