java之上传文件
2021/8/9 12:35:58
本文主要是介绍java之上传文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
依赖pom.xml
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency>
Spring bean配置
<!--文件上传id必须=multipartResolver--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--请求的编码格式,必须和jsp的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1--> <property name="defaultEncoding" value="utf-8"/> <!--上传文件大小上限,单位为字节10485760=10M--> <property name="maxUploadSize" value="10485760"/> <property name="maxInMemorySize" value="40960"/> </bean>
代码
@PostMapping("/article/upload1Handler") public String upload1Handler(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException { String uploadFileName = file.getOriginalFilename(); if ("".equals(uploadFileName)){ return "redirect:/article/index"; } System.out.println("上传文件名:" + uploadFileName); String path = request.getServletContext().getRealPath("/upload"); File realPath = new File(path); if (!realPath.exists()) { realPath.mkdir(); } System.out.println("上传文件地址:" + realPath); InputStream is = file.getInputStream();//文件输入流 BufferedInputStream bis = new BufferedInputStream(is); OutputStream os = new FileOutputStream(new File(realPath,uploadFileName));//文件输出流 BufferedOutputStream bos = new BufferedOutputStream(os); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { bos.write(buffer, 0, len); } bis.close(); bos.close(); return "redirect:/article/index"; } @PostMapping("/article/upload2Handler") public String upload2Handler(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException { String path = request.getServletContext().getRealPath("/upload"); File realPath = new File(path); if (!realPath.exists()) { realPath.mkdir(); } System.out.println("上传文件地址:" + realPath); //通过CommonsMultipartFile的方法直接写文件 file.transferTo(new File(realPath + "/" + file.getOriginalFilename())); return "redirect:/article/index"; }
视图
<form action="/article/upload2Handler" method="post" enctype="multipart/form-data"> <input type="file" name="file"/> <button type="submit">Submit</button> </form>
这篇关于java之上传文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-28知识管理革命:文档软件的新玩法了解一下!
- 2024-11-28低代码应用课程:新手入门全攻略
- 2024-11-28哪些办公软件适合团队协作,且能够清晰记录每个阶段的工作进展?
- 2024-11-28全栈低代码开发课程:零基础入门到初级实战
- 2024-11-28拖动排序课程:轻松掌握课程拖动排序功能
- 2024-11-28如何高效管理数字化转型项目
- 2024-11-28SMART法则好用吗?有哪些项目管理工具辅助实现?
- 2024-11-28深度剖析:6 款办公软件如何构建设计团队项目可视化管理新生态?
- 2024-11-28HTTP缓存课程:新手入门指南
- 2024-11-28实战丨证券 HTAP 混合业务场景的难点问题应对