Springmvc实现文件上传

网友投稿 237 2023-01-21


Springmvc实现文件上传

本文实例为大家分享了Springmvc实现文件上传的具体代码,供大家参考,具体内容如下

1.环境搭建:

在maven的pom.xml文件中导入两个依赖

1).commons-fileupload

2).commons-io

在resources目录下的springmvc.xml文件中配置multipartResolver

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xmlns:mvc="http://springframework.org/schema/mvc"

xsi:schemaLocation="

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context.xsd

http://springframework.org/schema/mvc

http://springframework.org/schema/mvc/spring-mvc.xsd

http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans.xsd">

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xmlns:mvc="http://springframework.org/schema/mvc"

xsi:schemaLocation="

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context.xsd

http://springframework.org/schema/mvc

http://springframework.org/schema/mvc/spring-mvc.xsd

http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans.xsd">

2.编写前台测试jsp

上传的文件:

密钥:

注意页面三要素:

1).表单提交方式必须为post

2).表单中必须有file域,即type="file"

   3).表单中enctype="multipart/form-data"

3.编写后台测试代码

@Controller

@RequestMapping("/test")

public class FileUploadController {

@RequestMapping("/file")

public String testFileUpload(HttpServletRequest request, MultipartFile upload) throws IOException {

//upload是表单中文件name属性值,必须保持一致

System.out.println("testFileUpload...");

String realPath = request.getSession().getServletContext().getRealPath("/uploads");

File file = new File(realPath);

if(!file.exists()){

file.mkdirs();//创建文件夹

}

String filename = upload.getOriginalFilename(); //获取文件名

String name = upload.getName();//获取表单中的name属性值 即upload

String uuid = UUID.randomUUID().toString().replaceAll("-", "");//生成uuid避免文件名重复导致冲突覆盖

filename=uuid+"_"+filename;

upload.transferTo(new File(file,filename));

return "forward:success.jsp";

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:java 泛型 实现接口(泛型类,泛型接口,泛型方法)
下一篇:详解Java 10 var关键字和示例教程
相关文章

 发表评论

暂时没有评论,来抢沙发吧~