欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

layui(1.0.9)文件上傳upload,前后端的實例代碼

 更新時間:2019年09月26日 16:53:12   作者:_New_  
今天小編就為大家分享一篇layui(1.0.9)文件上傳upload,前后端的實例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

因為公司還在使用老版本的layui,文件上傳在新版本中全部重寫了,這里記錄下老版本layui的文件上傳。

前端代碼:(引入layui相關(guān)包)

<input type="file" lay-type="file" id="xxxxx" name="file" class="layui-upload-file">

這里可以參考layui官方文檔,有一點需要注意,name屬性是必需的,當你選擇好文件后,name屬性的值,會在后臺被相應的參數(shù)接收。

如果你只寫了上面的代碼,會發(fā)現(xiàn)文件上傳的按鈕消失了。這很正常,因為框架就是這么設計的。

layui.upload({
  url: '/pay_channel/upload'
  ,before: function(input){
   //返回的參數(shù)item,即為當前的input DOM對象
   $(input).after('<input type="hidden" name="mchId-file" value="11111"/>');
   //layer.msg('文件上傳中',{zIndex:20180509});
  }
  ,success: function(res){
  if(res.code == 'success'){
   layer.msg(res.message,{zIndex:20180510});
   certLocalPath = res.filePath
  }else{
   layer.msg(res.message,{zIndex:20180510});
  }
  }

});

url是請求地址,必須是AJAX請求(POST),必須返回JSON,返回的數(shù)據(jù)在success中操作,以上代碼簡單易懂,不用照抄。

before是指在上傳請求進行之前,進行的一些操作,$(input).after('<input type="hidden" name="mchId-file" value="'+mchIdxx+'"/>');這段代碼是為了追加一個參數(shù),參數(shù)名字位mchId-file,值為11111,所以后端接收會有兩個參數(shù),file和mchId-file。

后端代碼:

  @RequestMapping("/upload")
  @ResponseBody
  public String importFile(MultipartFile file, HttpServletRequest request) {
   JSONObject object = new JSONObject();
      try {
       String mchId = request.getParameter("mchId-file");
       String originalFilename = file.getOriginalFilename();
//       String dirPath = System.getProperty("user.dir")+"/wx";
//       String dirPath = this.getClass().getClassLoader().getResource("").getPath()+"wx";
       String dirPath = "/xxxx/java/pay/wx/cert";
       _log.info("證書上傳的文件目錄{}", dirPath);
       String filePath = "/"+mchId+"_"+originalFilename;
  boolean b = new File(dirPath).mkdirs();
  file.transferTo(new File(dirPath + filePath).getAbsoluteFile());
  
  object.put("filePath", filePath);
  object.put("code", "success");
  object.put("message", "文件上傳成功");
  } catch (IOException e) {
  e.printStackTrace();
  object.put("code", "fail");
  object.put("message", "文件上傳失敗");
  }
      return object.toJSONString();

  }

獲得的file是MultipartFile類對象,org.springframework.web.multipart.MultipartFile

該對象可以獲取文件名字getOriginalFilename,獲取文件流getInputStream,傳輸?shù)搅硪粋€文件的方法transferTo等。

以上后端方法是將獲取到的文件,保存到另一個特別目錄中去。

再說幾句題外話:

String dirPath = System.getProperty("user.dir");//獲取項目地址根目錄,就是說你workspace中,該項目初始目錄。

String dirPath = this.getClass().getClassLoader().getResource("").getPath();//獲取項目resource目錄位置,即springboot中application.yml所在文件夾。

再windows中其實不需要寫盤符來表示這個目錄的絕對路徑,String dirPath = "/xxxx/java/pay/wx/cert";如果你項目在D盤,那絕對路徑就會變成D:/xxxx/java/pay/wx/cert,這樣就避免了服務器windows與linux的問題。

但有一點要注意:File file = new File(dirPath + filePath).getAbsoluteFile(),如果使用/開頭,需要用getAbsoluteFile()獲取到D:/xxxx/java/pay/wx/cert路徑的文件對象。

以上這篇layui(1.0.9)文件上傳upload,前后端的實例代碼就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論