这期内容当中小编将会给大家带来有关使用springboot怎么样实现一个文件上传下载功能,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
1.文件上传(前端页面):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="/testUpload" method="POST" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit" /> </form> <a href="/testDownload" rel="external nofollow" >下载</a> </body> </html>
表单提交加上enctype="multipart/form-data"很重要,文件以二进制流的形式传输。
2.文件上传(后端java代码)支持多文件
Way1.使用MultipartHttpServletRequest来处理上传请求,然后将接收到的文件以流的形式写入到服务器文件中:
@RequestMapping(value="/testUpload",method=RequestMethod.POST) public void testUploadFile(HttpServletRequest req,MultipartHttpServletRequest multiReq) throws IOException{ FileOutputStream fos=new FileOutputStream(new File("F://test//src//file//upload.jpg")); FileInputStream fs=(FileInputStream) multiReq.getFile("file").getInputStream(); byte[] buffer=new byte[1024]; int len=0; while((len=fs.read(buffer))!=-1){ fos.write(buffer, 0, len); } fos.close(); fs.close(); }
Way2.也可以这样来取得上传的file流:
// 文件上传 @RequestMapping("/fileUpload") public Map fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req) { Map result = new HashMap(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式 String dateDir = df.format(new Date());// new Date()为获取当前系统时间 String serviceName = UuidUtil.get32UUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); File tempFile = new File(fileDir + dateDir + File.separator + serviceName); if (!tempFile.getParentFile().exists()) { tempFile.getParentFile().mkdirs(); } if (!file.isEmpty()) { try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile)); // "d:/"+file.getOriginalFilename() 指定目录 out.write(file.getBytes()); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); result.put("msg", "上传失败," + e.getMessage()); result.put("state", false); return result; } catch (IOException e) { e.printStackTrace(); result.put("msg", "上传失败," + e.getMessage()); result.put("state", false); return result; } result.put("msg", "上传成功"); String fileId = Get8uuid.generateShortUuid(); String fileName = file.getOriginalFilename(); String fileType = fileName.substring(fileName.lastIndexOf(".") + 1); String fileUrl = webDir + dateDir + '/' + serviceName; uploadMapper.saveFileInfo(fileId, serviceName, fileType, fileUrl); result.put("state", true); return result; } else { result.put("msg", "上传失败,因为文件是空的"); result.put("state", false); return result; }
3.application.properties配置文件
#上传文件大小设置 multipart.maxFileSize=500Mb multipart.maxRequestSize=500Mb
4.文件下载将文件写到输出流里:
@RequestMapping(value="/testDownload",method=RequestMethod.GET) public void testDownload(HttpServletResponse res) throws IOException{ File file = new File("C:/test.txt"); resp.setHeader("content-type", "application/octet-stream"); resp.setContentType("application/octet-stream"); resp.setHeader("Content-Disposition", "attachment;filename=" + fileName); byte[] buff = new byte[1024]; BufferedInputStream bis = null; OutputStream os = null; try { os = resp.getOutputStream(); bis = new BufferedInputStream(new FileInputStream(file)); int i = bis.read(buff); while (i != -1) { os.write(buff, 0, buff.length); os.flush(); i = bis.read(buff); } } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
5.获取文件大小
// 文件大小转换 DecimalFormat df1 = new DecimalFormat("0.00"); String fileSizeString = ""; long fileSize = file.getSize(); if (fileSize < 1024) { fileSizeString = df1.format((double) fileSize) + "B"; } else if (fileSize < 1048576) { fileSizeString = df1.format((double) fileSize / 1024) + "K"; } else if (fileSize < 1073741824) { fileSizeString = df1.format((double) fileSize / 1048576) + "M"; } else { fileSizeString = df1.format((double) fileSize / 1073741824) + "G"; }
如果是File类则fileSize=file.length()。
上述就是小编为大家分享的使用springboot怎么样实现一个文件上传下载功能了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。