這個問題一直是新手學習extjs的問題,不知道怎麼回事也許是ext源碼的事也許是struts2的事,在網上搜尋了很多文章,解決方案也有很多種,試了很多種都不好使,現在解決了。我現在用的extjs版本是3.2的。 用struts2+ext開發上傳模組,上傳檔案成功,但總是在瀏覽器中有提示“下載”……看了一下下載的資料就是返回來的json字串,但是前台的回呼函數成功或失敗函數沒執行。解決方案首先是在action中直接寫
HttpServletResponse response = ServletActionContext.getResponse();response.setContentType("text/html;charset=UTF-8");
還有說是在Action中的傳回值從SUCCESS改為NONE
public String execute() throws IOException{ *******略******最後加上以下部分,struts設定檔正常,也不用配置text/html,完全沒有下載提示了……(不加入這個可能後續會有問題,暫時沒涉及呢,涉及了再說……) HttpServletResponse response = ServletActionContext.getResponse(); String msg = "{success:true}"; response.getWriter().print(msg); return NONE;}
<param name="contentType">text/html</param>這樣是解決,但是解決方案很特殊,就是不讓action往前台返回任何值,這樣當然不會出現下載框了,可是你的提示資訊都沒發送到前台我怎麼提示上傳成功還是失敗了呢,所以這個方法還是不行。
最後是在struts的設定檔中修改添加
<param name="contentType">text/html</param>
這個就好使了,追究其原因是,如果像第一種方法配置也行的,,但是最後都會被預設的contentType改寫的,所以第一種方法不行了。
最後把相關重要代碼貼上共參考
1.save Action中配置
public String save(){ String oldImageName = request.getParameter("oldImageName"); //是否上傳過,如果存在則刪除 if (!"noImage".equalsIgnoreCase(oldImageName)) { File oldFile = new File(ServletActionContext .getServletContext().getRealPath("/") + "UploadImages" + File.separator+oldImageName); oldFile.delete(); } System.out.println(oldImageName); //為使用者新上傳的圖片新取一個名字 try {user.setImage(writeFile("userPhoto"));userService.addUser(user);} catch (Exception e) {e.printStackTrace();message = e.getMessage();success = false;return NONE;} return NONE; }
2.struts 設定檔中配置
<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>
3.ext頁面中
register:function(btn){ this.form.getForm().submit({ waitMsg: '正在載入,請稍等……', waitTitle: '提示', url:'json2/FileUpload_save_Json', method: 'POST', scope:this, success: function(form,action){ this.setUser(action.result.user.image); }, failure: function(form, action) { Ext.Msg.alert('提示', '系統出錯,可能您的填寫有錯,請稍後再嘗試上傳!'); } }); },