Ajax实现文件上传(Spring MVC)
前端表单 和 JQuery jsp/html代码
使用JQuery
1 | < script src="static/js/jquery-3.4.1.js"></ script > |
前端表单
1 2 3 4 5 | < form id="form-avatar" enctype="multipart/form-data"> < p >请选择要上传的文件:</ p > < p >< input type="file" name="file" /></ p > < p >< input id="btn-avatar" type="button" value="上传" /></ p > </ form > |
ajax请求服务器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <script> function uploadfile(){ $.ajax({ url : "/url/upload" , data: new FormData($( "#form-avatar" )[0]), type : "POST" , // 告诉jQuery不要去处理发送的数据,用于对data参数进行序列化处理 这里必须false processData : false , // 告诉jQuery不要去设置Content-Type请求头 contentType : false , success : function (json) { alert( "执行成功" ); }, error : function (json) { alert( "执行失败" ); } }); } $( "#btn-avatar" ).on( "click" ,uploadfile); </script> |
导入maven依赖
<!--文件上传--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency>
并且配置spring mvc提供的文件上传的类
<!--文件上传配置--> <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"/> </bean>
Controller.java
1 2 3 4 5 6 7 8 9 10 11 12 13 | @PostMapping ( "/upload" ) public void fileUpload2( @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())); } |
!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!