最近接了一個小活,在短期內實現一個活動報名頁面,其中遇到了文件上傳。
我預期的效果是一次ajax post請求,而後在後臺java restlet的下面一次解決文件上傳和form表單的處理。一次搞定問題。固然這是個人預期,真正實現起來仍是不太順利。javascript
在網上頗有不少文件上傳的例子(嘗試了uploadify,ajaxfileupload),但是很遺憾,在我這裏好像都沒有成功!
苦於本身的javascript水平太菜,也沒有帶多的精力來弄,
而後在google的幫助下 在這裏,這裏,這裏的指引下,終於能夠實現我要的效果.css
ajax post => form + file (formdata) => restlet後臺處理html
期間也簡單瞭解了一下rf1867, 以及老趙的bloghtml5
下面具體說說代碼部分。java
html部分:jquery
<html> <header> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script> </header> <body> <h1>*****Upload File with RESTFul WebService*****</h1> <form id = "myform" > <fieldset> <legend>Upload File</legend> <input type="file" id ="fileToUpload" name="fileToUpload"/><br /> <br /><br /> Party ID<input type="text" id = "partyid" name="partyid" /><br /> <a id="submit" href="javascript:void(0);" >提交</a> </fieldset> </form> <script type="text/javascript"> $("#submit").click( function(){ var partyid = $("#partyid").val(); var fileToUpload = $("#fileToUpload").val(); var options = { 'event': 'xxxx2015', 'info': { 'partyid': partyid, 'fileToUpload': fileToUpload, } }; //file upload console.log($("#myform").serialize()) console.log(fileToUpload) console.log(partyid) var formData = new FormData(); formData.append( 'fileToUpload', $( '#fileToUpload' )[0].files[0] ); formData.append( 'partyid', partyid); $.ajax({ url: '../restful/v1.0/api/app/enroll/upload?token=JA1mqLiXDgcZ0ijJhE9R', type: "POST", contentType: false, cache: false, processData: false, data: formData, dataType: "json", success: function (res) { if (res.status) { alert('註冊成功!電子票已發送到你的手機/郵箱'); console.log(res); } else { switch (res.message) { case 'hasApplied': $('#user_info').text(''); alert('您已報名過這次大會,無需重複報名'); break; default : console.log(res.message); alert('啊哦~圖片提交失敗,請重啓提交'); break; } } }, error: function (res) { alert('啊哦~圖片提交失敗,請重啓提交'); } }); }); </script> </body>
最主要是是ajax中這三行:ajax
contentType: false, cache: false, processData: false,
後臺代碼部分 springmvc + restlet:spring
public class EnrollFileUploadResource extends ServerResourceBase{ private static Logger logger = Logger.getLogger(EnrollFileUploadResource.class.getName()); private EnrollRegisterService enrollRegisterService; String parameter=""; @Override protected void doInit() throws ResourceException { logger.info("開始執行"); super.doInit(); } @Post public Representation createTransaction(Representation entity) { Representation rep = null; JSONObject json=new JSONObject(); if (entity != null) { if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { // 1/ Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000240); // 2/ Create a new file upload handler RestletFileUpload upload = new RestletFileUpload(factory); List<FileItem> items; try { Request req = getRequest(); // 3/ Request is parsed by the handler which generates a list of FileItems items = upload.parseRequest(req); Map<String, String> props = new HashMap<String, String>(); File file = null; String filename = null; for (final Iterator<FileItem> it = items.iterator(); it.hasNext(); ) { FileItem fi = it.next(); String name = fi.getName(); if (name == null) { props.put(fi.getFieldName(), new String(fi.get(), "UTF-8")); } else { try { String tempDir = getClass().getClassLoader().getResource("").getPath(); tempDir = tempDir.substring(0,tempDir.lastIndexOf("WEB-INF")); String osName = System.getProperty("os.name"); if(osName.toLowerCase().indexOf("windows")>-1){ tempDir = tempDir.substring(1, tempDir.length()); } String uploadingPath = tempDir + "static" + File.separatorChar +"uploading"; File f = new File(uploadingPath); if (!f.exists()) { f.mkdirs(); } String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); String str=name.substring(name.lastIndexOf(".")); filename = time + RandomUtil.getStringCode(8)+str; file = new File(uploadingPath+ File.separator+ filename); fi.getInputStream(); fi.write(file); props.put("image", filename); } catch (Exception e) { e.printStackTrace(); json.put("status", false); json.put("message","fileUploadFail"); // 已經報過名了 } } } // [...] my processing code EnrollUser user =new EnrollUser(); user.setEvent(props.get("event")); user.setUserName(props.get("userName")); user.setMobile(props.get("mobile")); 。。。 user.setImage(props.get("image")); user.setCreate_time(TimeUtil.getNowTimeByPattern(TimeUtil.DATE_DEFAULT_PATTERN)); if(enrollRegisterService.hasEnrolled(user)) { json.put("status",false); json.put("message","hasApplied"); // 已經報過名了 } else { enrollRegisterService.saveOrUpdateData(user); json.put("status",true); json.put("info","成功"); } } catch (Exception e) { // The message of all thrown exception is sent back to // client as simple plain text getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); e.printStackTrace(); rep = new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN); } } else { // other format != multipart form data getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); rep = new StringRepresentation("Multipart/form-data required", MediaType.TEXT_PLAIN); } } else { // POST request with no entity. getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); rep = new StringRepresentation("Error", MediaType.TEXT_PLAIN); } json.put("status",true); return new StringRepresentation(json.toString()); } public void setEnrollRegisterService(EnrollRegisterService enrollRegisterService) { this.enrollRegisterService = enrollRegisterService; } }
完畢。json
至於配置springmvc +restlet的配置環境如何,這裏就再也不說明。windows
若有問題,歡迎討論。