SpringMVC文件上传实现

a 夏天 提交于 2020-02-08 18:25:36

文件上传的必要前提:
    1.form表单的enctype取值必须是:multipart/form-data(默认值是:application/x-www-form-urlencoded)
enctype:是表单请求正文的类型
    2.method属性取值必须是Post
    3.提供一个文件选择域
    借助第三方组件实现:
    需要导入的jar包:

<dependency>
     <groupId>commons-fileupload</groupId>
     <artifactId>commons-fileupload</artifactId>
     <version>1.3.1</version>
</dependency>
<dependency>
     <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>2.4</version>
</dependency>

    主要的jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>传统方式文件上传</h3>
<form action="user/fileUpload" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload"/><br/>
    <input type="submit" value="上传"/>
</form>
<h3>springmvc方式文件上传</h3>
<form action="user/fileUpload2" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload"/><br/>
    <input type="submit" value="上传"/>
</form>
<h3>跨服务器方式文件上传</h3>
<form action="user/fileUpload3" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload"/><br/>
    <input type="submit" value="上传"/>
</form>
</body>
</html>
一、传统文件上传方式

    1.导入文件上传的jar包

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

    2.编写控制器方法

@RequestMapping("/fileUpload")
    public String fileUpload(HttpServletRequest request) throws Exception {
        System.out.println("文件上传");
        //上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //判断是否存在
        File file = new File(path);
        if (!file.exists()){
            //创建该文件夹
            file.mkdirs();
        }
        //解析request对象,并获取上传文件项
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解析request
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()){
                //普通表单项
            }else {
                //上传文件项
                //获取文件名
                String name = item.getName();
                //把文件名设置为唯一值,uuid
                String uuid = UUID.randomUUID().toString().replace("-", "");
                name = uuid+"_"+name;
                //完成文件上传
                item.write(new File(path,name));
                //删除临时文件
                item.delete();
            }
        }
        return "success";
    }
}
二、Springmvc方式文件上传

    Springmvc框架提供了MultipartFile对象,该对象表示上传的文件,要求变量名称必须和表单file标签的nam属性名称相同
    1.springmvc.xml中配置文件解析器

<!--配置文件解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10485760"></property>
</bean>

    2.编写控制器方法

@RequestMapping("/fileUpload2")
public String fileUpload2(HttpServletRequest request, MultipartFile upload) throws Exception {
    System.out.println("springmvc文件上传");
    //上传的位置
    String path = request.getSession().getServletContext().getRealPath("/uploads/");
    //判断是否存在
    File file = new File(path);
    if (!file.exists()){
        //创建该文件夹
        file.mkdirs();
    }
    //上传文件项
    //获取文件名
    String name = upload.getOriginalFilename();
    //把文件名设置为唯一值,uuid
    String uuid = UUID.randomUUID().toString().replace("-", "");
    name = uuid+"_"+name;
    //完成文件上传
    upload.transferTo(new File(path,name));
    return "success";
}
三、SpringMVC跨服务器方式文件上传

    1.搭建两个tomcat服务器
    2.导入需要的jar包

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.18.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.18.1</version>
</dependency>

    3.编写控制器方法

@RequestMapping("/fileUpload3")
public String fileUpload3(MultipartFile upload) throws Exception {
    System.out.println("跨服务器文件上传");
    //定义上传文件服务器路径
    String path = "http://localhost:9090/uploads/";
    //上传文件项
    //获取文件名
    String name = upload.getOriginalFilename();
    //把文件名设置为唯一值,uuid
    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    name = uuid+"_"+name;
    //创建客户端对象
    Client client = Client.create();
    //和服务器连接
    WebResource webResource = client.resource(path+name);
    //文件上传
    webResource.put(upload.getBytes());
    return "success";
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!