<form id="upload"> <input type="file" id="image" name="image" /> </form>采用Ext ajax提交form,并设置上传参数
Ext.Ajax.request({ url : "upload.action",isUpload : true,form : "upload",success : function(response) { var jsonObj = Ext.JSON.decode(response.responseText); if (0 == jsonObj.result) alert("上传成功"); else alert("上传失败"); } });后台使用的是struts2架构,只需要在对应的action类中定义同名的File参数获取文件信息
private File image; public File getImage(){ return image; } public void setImage(File image){ this.image = image; }然后再对应的action处理方法中直接对image对象进行操作
public String upload() throws Exception{ if (map != null && image.isFile()){ BufferedInputStream bis = new BufferedInputStream(new FileInputStream(image)); byte[] buff = new byte[(int) map.length()]; bis.read(buff); result = 0; return SUCCESS; } else{ result = 1; return ERROR; } }操作结果以json形式返回给页面,result值为0表示成功,1表示失败。但是发现返回的json数据被封转多一个<pre>标签
<pre style="word-wrap: break-word; white-space; pre-wrap; ">{"result":0}</pre>
这是由于浏览器自动给返回结果封装成html,详细可看Ext说明文档http://docs.sencha.com/ext-js/4-0/#/api/Ext.form.Basic-method-hasUpload
这是由于浏览器自动给返回结果封装成html,详细可看Ext说明文档http://docs.sencha.com/ext-js/4-0/#/api/Ext.form.Basic-method-hasUpload
<action name="upload" class="com.UploadAction" method="upload"> <result name="success" type="json"> <param name="contentType">text/html</param> <param name="includeProperties"> result </param> </result> <result name="error" type="json"> <param name="contentType">text/html</param> <param name="includeProperties"> result </param> </result> </action>