SpringMVC achieve file upload

Prerequisite uploaded file:
    1.form form enctype value must be: multipart / form-data (default is: file application / X-WWW-form-urlencoded)
enctype: request type is a form of body
    2.method attribute takes the value must be Post
    3. provide a file selection field
    with third-party components to achieve:
    to be imported jar package:

<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>

    The main jsp page

<%@ 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>
First, the traditional file uploads

    1. Import jar package file upload

<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. Write controller method

@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";
    }
}
Two, Springmvc way file uploads

    Springmvc framework provides MultipartFile object that represents the uploaded files, and requires a variable name must be the same nam attribute name of the form file label
    configuration file parser in 1.springmvc.xml

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

    2. Write controller method

@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";
}
Three, SpringMVC way across the server file upload

    1. Building Two tomcat servers
    2. Import required jar package

<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. Write controller method

@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";
}
Published 23 original articles · won praise 3 · Views 338

Guess you like

Origin blog.csdn.net/weixin_45636641/article/details/104226137