日期:2014-05-16  浏览次数:20438 次

后台返回json数据,提示下载保存
这个问题有点烦,问题解决了,但道理没有弄明白转载一个最有帮助的文章吧http://guofengcn.iteye.com/blog/655370
用struts2+ext开发上传模块,上传文件成功,但总是在浏览器中有提示“下载”……

    而且发现前台的success和failure都没有执行到,打印json串一切正常……

   

    这就奇怪了~~~上网找原因……发现好多人遇到这种问题,按网上的说法一步一步的试,首先是在struts配置文件中加入:

Xml代码
1.<param name="contentType">text/html</param> 
<param name="contentType">text/html</param>    还是没解决掉……



    换个方式,在action中直接写:

Java代码
1.HttpServletResponse response = ServletActionContext.getResponse();  
2.response.setContentType("text/html;charset=UTF-8"); 
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=UTF-8");
   试了下,还是不行……

   还有说把struts配置文件中的:<result type="json">中的json改为XXX的……没有去尝试!



    说正题,解决方式~

    经过无数次的尝试后发现,其实只要将Action中的返回值从SUCCESS改为NONE,并写……

Java代码
1.public String execute() throws IOException{  
2.       *******略******最后加上以下部分,struts配置文件正常,也不用配置text/html  
3.,完全没有下载提示了……(不加入这个可能后续会有问题,暂时没涉及呢,涉及了再说……)  
4.     HttpServletResponse response = ServletActionContext.getResponse();  
5.       String msg = "{success:true}";  
6.       response.getWriter().print(msg);  
7.       return NONE;  
8.} 
public String execute() throws IOException{
       *******略******最后加上以下部分,struts配置文件正常,也不用配置text/html
,完全没有下载提示了……(不加入这个可能后续会有问题,暂时没涉及呢,涉及了再说……)
     HttpServletResponse response = ServletActionContext.getResponse();
       String msg = "{success:true}";
       response.getWriter().print(msg);
       return NONE;
}    到现在为止,下载问题应该不会再出现了……



    谁能有更好的解决方式麻烦告诉我一下……


以下是二楼的回复,也很有帮助
我试了你的第一个方法还解决了:firfox不再弹出下载对话框,序列化的action照样能接受,Ext form提交后的回调函数正常执行,谢了,呵呵
不知道你为什么没成功,我把重要代码,提出来,你自己对照看看,说不定能有所收获:
1.save action方法:

Java代码
1.public String save(){   
2.       String oldImageName = request.getParameter("oldImageName"); //是否上传过,如果存在则删除     
3.       if (!"noImage".equalsIgnoreCase(oldImageName)) {       
4.           File oldFile = new File(ServletActionContext     
5.               .getServletContext().getRealPath("/")     
6.               + "UploadImages" + File.separator+oldImageName);     
7.           oldFile.delete();  
8.       }     
9.       System.out.println(oldImageName); //为用户新上传的图片新取一个名字       
10.       try {  
11.        user.setImage(writeFile("userPhoto"));  
12.        userService.addUser(user);  
13.    } catch (Exception e) {