介绍
这篇文章给大家分享的是有关springmvc怎样实现文件上传功能的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
一个简单的springmvc文件上传例子
<强>所需的依赖强>
只需要这个就好了,在想法的依赖关系图中,commons-fileupload包含了commons-io依赖
& lt; dependency> & lt;才能groupId> commons-fileupload</groupId> & lt;才能artifactId> commons-fileupload</artifactId> & lt;才能version> 1.3.2</version> & lt;/dependency>
一个简单的文件上传的页面
& lt; form action=癶ttp://localhost: 8080/springmvc_Web_exploded/fff",方法=皃ost", enctype=岸嗖糠?form-data"比; ,& lt; input 类型=癴ile", name=癴ile", id=癴iler_input",多个=癿ultiple"比; ,& lt; input 类型=皊ubmit",值=https://www.yisu.com/zixun/疤峤弧? 形式>
在春天的配置文件中注入一个文件上传的bean
春季。xml
& lt; !——,文件上传的bean——比; ,& lt; bean id=癿ultipartResolver" 类,,=皁rg.springframework.web.multipart.commons.CommonsMultipartResolver"比; & lt;才能!——上传文件的最大大小,单位为字节,——比; & lt;才能property name=癿axUploadSize" https://www.yisu.com/zixun/, value=" 17367648787 "> 属性> <属性名=" defaultEncoding " value=" utf - 8 "> 属性> 豆>
实例代码
@PostMapping (“/fff") ,public String 文件(@PathVariable (“file") MultipartFile 文件,,HttpServletRequest 要求),throws IOException { ,//判断文件不存在 if 才能;(file.isEmpty ()) { ,,return “faile.html"; ,,}//我才能想放到这个地方文件的路径 String 才能;realPath =, req.getServletContext () .getRealPath (“/web - inf/file");//才能返回客户端文件系统中的原始文件名 String 才能;filename =, file.getOriginalFilename (); File 才能;myFile =, new 文件(realPath,文件名); if 才能;(! myFile.getParentFile () .exists ()) { ,,myFile.getParentFile () .mkdir (); ,,System.out.println(“文件夹被创建了“); ,,} ,//将前端传过来的文件,传到自己新的的文件对象中 file.transferTo才能(myFile); return 才能“success.html"; ,}
<强>注意事项:强>
1,文件上传请求必须用<强>文章强>请求。
2,注意路径问题
3,前端的<>强形式表单>强必须添加<强> enctype=岸嗖糠?form-data">强这个属性