springboot实现文件上传下载
程序员文章站
2022-05-01 08:09:26
...
-
单文件上传
// 后端实现代码 @ResponseBody @RequestMapping("uploadFile") public String uploadFile(@RequestParam("fileName")MultipartFile file) { if (file.isEmpty()) { return "false"; } // getOriginalFilename()方法获取上传文件的文件名 String originalname = file.getOriginalFilename(); // getSize()方法获取上传文件大小 int size = (int)file.getSize(); System.out.println(originalname+"-->"+size); // 设置文件路径、新文件名 String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/upload"; String randomStr = UUID.randomUUID().toString().replaceAll("-",""); String newFileName = randomStr+"_"+originalname; // 指定上传文件要保存到的文件位置 File f = new File(path,newFileName); if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } try { // 保存文件 file.transferTo(f); return "true"; } catch (IOException e) { e.printStackTrace(); return "false"; } }
<!-- html页面代码 --> <h1 th:inlines="text">文件上传</h1> <form action="uploadFile" method="post" enctype="multipart/form-data"> <p>选择文件: <input type="file" name="fileName"/></p> <p><input type="submit" value="提交"/></p> </form>
-
多文件上传
// 后端实现代码 @RequestMapping(value = "uploadMultiFile",method = RequestMethod.POST) // @ResponseBody // public String //uploadMultiFile(@RequestParam("fileName")List<MultipartFile> files) { public @ResponseBody String uploadMultiFile(HttpServletRequest request) { List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("fileName"); if (files.isEmpty()) { return "false"; } String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/upload"; for (MultipartFile file : files) { String originalname = file.getOriginalFilename(); String randomStr = UUID.randomUUID().toString().replaceAll("-",""); String newFileName = randomStr+"_"+originalname; File f = new File(path,newFileName); if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } try { // 保存文件 file.transferTo(f); } catch (IOException e) { e.printStackTrace(); return "false"; } } return "true"; }
<!-- html页面代码 --> <h1 th:inlines="text">文件上传</h1> <form action="uploadMultiFile" method="post" enctype="multipart/form-data" > <p>选择文件1: <input type="file" name="fileName"/></p> <p>选择文件2: <input type="file" name="fileName"/></p> <p>选择文件3: <input type="file" name="fileName"/></p> <p><input type="submit" value="提交"/></p> </form>
-
文件和表单数据一起上传
// controller控制层代码 @ResponseBody @RequestMapping("upload_deal") public String upload_deal(AgentVo agentVo) throws Exception{ System.out.println(agentVo.getAgentName()); System.out.println(agentVo.getAgentPhone()); MultipartFile blfile = agentVo.getBlFile(); if (!blfile.isEmpty()) { String originalFilename = blfile.getOriginalFilename(); String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/upload"; String randomStr = UUID.randomUUID().toString().replaceAll("-",""); String newFileName = randomStr + originalFilename.substring(originalFilename.lastIndexOf(".")); File file = new File(path,newFileName); System.out.println(file); if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } blfile.transferTo(file); } return "true"; }
// 后端接收实体类 public class AgentVo implements Serializable { private Integer id; private String agentName; private String agentPhone; private MultipartFile blFile; private static final long serialVersionUID = 1L; .......// 这里省略getter、setter }
-
<!-- html页面代码(表单提交实现) --> <div id="uploadTest"> <form id="upload_deal" action="upload_deal" method="POST" enctype="multipart/form-data"> 代理人名称:<input type="text" name="agentName" /><br/> 代理人手机号:<input type="text" name="agentPhone" /><br/> 营业执照:<input type="file" name="blFile" /><br/> <input type="submit" value="提交" id="submitBnt"> </form> </div>
-
<!-- html页面代码(js实现) --> <div style="margin:30px 50px"> <label>用户名</label> <input type="text" id="agentName" name="agentName"><br/> <label>联系方式</label> <input type="text" id="agentPhone" name="agentPhone"><br/> <input type="file" id="blFile" name="blFile" /><br/> <input type="button" onclick="UpladFile()" value="上传" /> <input type="button" value="取消" /> </div> <!-- js代码部分 --> <script type="text/javascript"> //文件上传 var xhr; //上传文件方法 function UpladFile() { var fileObj = document.getElementById("blFile").files[0]; // js 获取文件对象 var username = document.getElementById('agentName').value; var sex = document.getElementById('agentPhone').value; var url = "upload_deal"; // 接收上传文件的后台地址 var form = new FormData(); // FormData 对象 form.append("blFile", fileObj); // 文件对象 form.append("agentName",username); form.append("agentPhone",sex); $.ajax({ url:url, type:"post", data:form, processData:false, contentType:false, success:function (data) { if (data == true) { alert("上传成功"); window.location.reload(); } else { alert("上传失败"); window.location.reload(); } } }); } </script>
-
-
文件下载
// 后端代码实现(前端就用a标签完成就可以,此处忽略) @RequestMapping("download") public void download(HttpServletResponse response) { // 这部分用来写文件路径、文件名获取逻辑,本例中直接使用了上传到项目中的文件 String fileName = "E:\\project\\filedemo\\target\\classes\\static\\upload\\0a8c3abe15b748a28b96cf5ced020cf6.jpg"; // 设置响应头 response.setHeader("content-type","application/octet-stream"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition","attachment;filename="+fileName); // 文件传输 byte[] buff = new byte[1024]; BufferedInputStream bis = null; OutputStream os = null; try { os = response.getOutputStream(); bis = new BufferedInputStream(new FileInputStream(fileName)); int i = bis.read(buff); while (i != -1) { os.write(buff,0,buff.length); os.flush(); i = bis.read(buff); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (Exception e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (Exception e) { e.printStackTrace(); } } } }
上一篇: Spring Boot 自定义日志配置
下一篇: spring boot启动自定义配置