fastDFS+LibreOffice多檔案上傳(二)後端部分:檔案資訊轉json字串儲存資料庫(Gson和org.json兩種方式)
阿新 • • 發佈:2018-11-19
需要注意的地方:
1)如果你複製我的程式碼到你的程式上報錯,可以看看我第一篇文章實體類跟配置檔案的設定:https://blog.csdn.net/qq_36688143/article/details/84162924
第二篇檔案上傳前端頁面的程式碼:
https://blog.csdn.net/qq_36688143/article/details/84164885
2)提供兩種方式轉換檔案資訊以json字串形式儲存到資料庫,Gson和org.json,轉換程式碼在我的另一篇介紹各種Json的部落格裡有寫:https://blog.csdn.net/qq_36688143/article/details/84135660
3)fastDFS負責上傳下載的server設定
@Autowired
private FastDFSTemplate fastDFSTemplate;
4) 方法頭中接收檔案引數的設定
@RequestParam("uploadFile") CommonsMultipartFile[] files
// 二選一
MultipartFile[] files
5)判斷檔案是否非空
for(MultipartFile file:files) { if (StringUtils.isNotBlank(file.getOriginalFilename())){} }
6)上傳的主要方法
// 檔案上傳,引數為檔案byte,檔案字尾
FastDfsInfo fastDfsInfo = fastDFSTemplate.upload(file.getBytes(), ext);
// 轉換檔案到介面顯示類
FileInfo fileInfo = new FileInfo(file.getOriginalFilename(), ext, fastDfsInfo);
完整程式碼
@RequestMapping(value = "save") public String save(@RequestParam("uploadFile") CommonsMultipartFile[] files, HttpServletRequest request, HttpServletResponse response) { Gson gs = new Gson(); List<FileInfo> fileInfos = new ArrayList<FileInfo>(); for(MultipartFile file:files) { // 如果選擇了上傳檔案 if (StringUtils.isNotBlank(file.getOriginalFilename())){ long sizeL = file.getSize(); String size = FileInfo.getPrintSize(sizeL); String ext = file.getOriginalFilename().split("\\.")[1]; String name = file.getOriginalFilename().split("\\.")[0]; try { // 檔案上傳,引數為檔案byte,檔案字尾 FastDfsInfo fastDfsInfo = fastDFSTemplate.upload(file.getBytes(), ext); // 轉換檔案到介面顯示類 FileInfo fileInfo = new FileInfo(file.getOriginalFilename(), ext, fastDfsInfo); fileInfo.setTitle(name); fileInfo.setSize(size); // 封裝附件attachment fileInfos.add(fileInfo); } catch (FastDFSException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } String listStr = ""; if (fileInfos.size() != 0){ listStr = gs.toJson(fileInfos);//把List轉為JSON格式的字串 } // 存入資料庫 noticeService.save(listStr); return "redirect:" + Global.getAdminPath() + "/info/notice/record"; }