springboot上传文件并保存到数据库

Crazy晓枫 Crazy晓枫 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
@PostMapping("/UploadFile") @ResponseBody public String uploadFile(@RequestParam MultipartFile file, HttpServletRequest request) { if (file.isEmpty()) { return "-1"; } String uploadTempFloder ="/upload/"; logger.info("upload starting........"); //得到上传的文件名 String originalFilename = file.getOriginalFilename(); logger.info("上传文件名:" + originalFilename); //后缀名 String suffix = originalFilename.substring(originalFilename.lastIndexOf("."),originalFilename.length()); //保存到资源表中 Asset asset = new Asset(); asset = Asset.insertBean(asset); //设置值 asset.setAssetName(originalFilename); asset.setAssetType(file.getContentType()); asset.setFileSize(file.getSize()); assetService.inserAsset(asset); //得到文件 并且改名 String storePath = uploadTempFloder + DateUtil.getSystemDateStr()+"/" + asset.getId() +suffix; asset.setStorePath(storePath); assetService.updateAsset(asset); //全路径 String fileAllPath = uploadPath + uploadTempFloder + DateUtil.getSystemDateStr()+"/" + asset.getId() +suffix; File newFile = new File(fileAllPath); if (!newFile.getParentFile().exists()){ newFile.getParentFile().mkdirs(); } try { FileUtil.writeIntoOut(file.getInputStream(),new FileOutputStream(storePath)); } catch (IOException e) { return "-1"; } logger.info("upload finish........"); return CastUtil.castString(asset.getId()); } public static void writeIntoOut(InputStream ins, OutputStream out) { try { if (ins != null && out != null) { byte[] arr = new byte[10 * 1024]; int len = ins.read(arr); while (len > 0) { out.write(arr, 0, len); len = ins.read(arr); } } } catch (Exception e) { throw new RuntimeException(e); } finally { if (ins != null) { try { ins.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } 上传post请求、、 uploadFile 然后在action中这么处理, Asset 是对应的资源表,FileUtil.writeIntoOut 是第二段代码,复制文件 ,
...全文

相关推荐

评论
收藏 已收藏
分享
返回顶部
Crazy晓枫
Eclipse 58,439 成员 49,457 内容