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

Crazy晓枫 2019-05-17 12:19:19
@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 是第二段代码,复制文件 ,
...全文
1646 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

58,454

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧