ExtJs+Jersey上传文件
qalong
2013-01-25
这里太安静了发个帖子分享经验吧
当使用ExtJs默认提供的上传方法与Jersey一块使用的时候碰到了两个头疼的问题,在此记下来给大家提个醒。 主要有两个地方要注意 1.当使用ExtJs表单提交到Jersey服务端端上传文件的时候,服务端代码要设置成 @Produces(MediaType.TEXT_HTML) 否则在前台ExtJs转化Json对象的时候会报 uncaught exception: You're trying to decode an invalid JSON String: <pre>{"success":true,"errorCode":-1,"error":""}</pre 参考:http://stackoverflow.com/questions/9716694/have-issue-with-response-of-submit-in-extjs-response-in-json-but-somewhere-html 2.ExtJs回执事件每次都到failure,不走success 其实ExtJs可以解析json格式的表单回执消息,格式为 {"success":true,....} 只要添加上这段就可以,根据success自动走success和failure代码了 完整代码: Ext.require(['Ext.form.field.File', 'Ext.form.Panel', 'Ext.window.MessageBox']); Ext.onReady(function() { Ext.create('Ext.form.Panel', { renderTo : Ext.getBody(), width : 500, frame : true, title : 'File Upload Form', bodyPadding : '10 10 0', defaults : { anchor : '100%', allowBlank : false, msgTarget : 'side', labelWidth : 30 }, items : [{ xtype : 'filefield', id : 'form-file', emptyText : 'Select an file', fieldLabel : 'File', name : 'filePath', buttonText : '', buttonConfig : { iconCls : 'upload-icon' } }], buttons : [ { text : 'Save', handler : function() { var form = this.up('form').getForm(); if (form.isValid()) { form.submit({ url : webRoot + 'rest/file/upload2', waitMsg : '正在上传文件...', success : function(form, action) { Ext.MessageBox.alert('成功','成功上传文件 "' + action.result.fileName+ '" 到服务器'); }, failure : function(form, action) { Ext.MessageBox.alert('失败','上传文件失败'); } }); } } }, { text : 'Reset', handler : function() { this.up('form').getForm().reset(); } }] }); }); import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.stereotype.Component; @Path(value = "file") @Component public class FileUpAndDownCtrl { class UploadRespnse implements Serializable { private String fileName; private Boolean success = false;; public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public Boolean getSuccess() { return success; } public void setSuccess(Boolean success) { this.success = success; } } @POST @Produces(MediaType.TEXT_HTML) /* 此处必须设置为TXT_HTML,否则ExtJS前台不能获得正确的返回 */ @Path(value = "upload2") public String loadFile(@Context HttpServletRequest request) throws JsonGenerationException, JsonMappingException, IOException { UploadRespnse res = new UploadRespnse(); String fileRepository = "c:/files/"; if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } if (items != null) { Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (!item.isFormField() && item.getSize() > 0) { String fileName = processFileName(item.getName()); try { item.write(new File(fileRepository + fileName)); res.setSuccess(true); res.setFileName(fileName); } catch (Exception e) { e.printStackTrace(); res.setSuccess(false); } } } } } ObjectMapper ob = new ObjectMapper(); String resStr = ob.writeValueAsString(res); return resStr; } private String processFileName(String fileNameInput) { String fileNameOutput = null; fileNameOutput = fileNameInput.substring(fileNameInput.lastIndexOf("\\") + 1, fileNameInput.length()); return fileNameOutput; } } |