傳統form表單提交方式的檔案上傳與檔案儲存
阿新 • • 發佈:2019-01-05
引言
時隔一天,上一篇文章《檔案儲存》剛一停筆,今天上午就解決了困擾我已久的檔案上傳問題。
站在一個已實現功能的角度來重新看待這個檔案上傳的業務:編輯頁面選擇jar包,然後通過form表單提交,上傳到後臺程式,然後儲存。
對於後端實現的更多細節,可以參考我的另一篇技術分享《Java實現使用者頭像上傳》,裡面較為詳細的分析了檔案從瀏覽器傳輸到伺服器之後的一些處理規則,包括接收方式、磁碟儲存等。
檔案上傳的入口
最簡單的瀏覽器上傳入口僅需要一個form標籤:
<form action="http://localhost:8081/thingsparse/addorupdthingsparse" method="post" enctype="multipart/form-data"> <input type="file" name="file" value="選擇jar包"/> <input id="submit_form" type="submit" class="btn btn-success save" value="儲存"/> </form>
前端只是用了傳統的form表單上傳檔案的方式,提交按鈕直接submit到後臺,而不需要多寫哪怕一丁點的額外js。
值得注意的是:每條form表單引數都需要有name屬性,以及form表單的enctype="multipart/form-data"。
檔案的儲存
其實關鍵的程式碼就是檔案的接收,至於後面的儲存操作,基本上都是對IO流的操作。瀏覽《Java實現使用者頭像上傳》參考更多資訊。
/** * 解析新建編輯 * * @param String * newThingsParse是一個擁有ThingsParse類結構的json字串 * @return */ @RequestMapping(value = "/addorupdthingsparse") public ModelAndView saveThingsParse(MultipartFile file, HttpServletRequest request) { String idStr = request.getParameter("thingsparse_id"); ThingsParse thingParse = new ThingsParse();//將被儲存於mongodb的例項 String filePath = "";// jar包的路徑 if (!file.isEmpty()) { File temp = new File(""); filePath = temp.getAbsolutePath() + "\\" + file.getOriginalFilename(); BufferedOutputStream out; try { out = new BufferedOutputStream(new FileOutputStream(new File(filePath))); out.write(file.getBytes()); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } logger.info("儲存的jar包路徑是:" + filePath);//output:儲存的jar包路徑是:D:\workspace\wxgz\json.jar thingParse.setJarPackage(filePath); thingParse.setAuthor(request.getParameter("author")); thingParse.setDirection(request.getParameter("direction")); thingParse.setEntranceClass(request.getParameter("entrance_class")); thingParse.setEntranceMethod(request.getParameter("entrance_method")); thingParse.setName(request.getParameter("thingsparse_name")); thingParse.setTestData(request.getParameter("test_data")); thingParse.setVersion(request.getParameter("version")); if (idStr == null || "".equals(idStr)) {// 新增 // 獲取當前系統時間 Calendar now = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String nowStr = sdf.format(now.getTime()); // 將物解析例項的建立時間賦值 thingParse.setCreateTime(nowStr); // 儲存 thingsParseRepository.save(thingParse); } else {// 編輯 thingParse.set_id(new ObjectId(idStr)); if(file.isEmpty()){ thingParse.setJarPackage(request.getParameter("jar_package")); } thingParse.setCreateTime(request.getParameter("thingsparse_createtime")); thingsParseRepository.save(thingParse); } String listUrl = "redirect:http://localhost:8081/thingsparse/thingsparselist"; return new ModelAndView(listUrl);//後臺重定向 }
總結
web應用的檔案上傳是一個相對通用的功能,使用最簡單的form表單提交基本可以滿足多數應用的要求。
關鍵的思路就是前端的form表單選擇檔案然後提交,後端使用型別MultipartFile 接收。而檔案儲存到本地磁碟可以參考《檔案儲存》和《Java實現使用者頭像上傳》。