SpringMVC黑马:SpringMVC实现文件上传

文章目录

  • 1.传统文件上传方式
  • 2. SpringMVC实现文件上传
  • 3. SpringMVC跨服务器方式文件上传

1.传统文件上传方式

pom.xml配置

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

index.jsp

<h3>传统文件上传</h3>
    <form action="user/fileupload1" method="post" enctype="multipart/form-data">
      选择文件:<input type="file" name="upload"/><br>
      <input type="submit" value="上传">
    </form>

控制层controller

/**传统文件上传方式*/
@Controller
@RequestMapping(value = "/user")
public class FileUpload {
    /**文件上传*/
    @RequestMapping("/fileupload1")
    public String fileupload1(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("传统文件上传:fileupload1文件上传。。");
        //使用fileupload组件完成文件上传
        //上传的位置,通过session获取ServletContext对象,再获取绝对路径
        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) {
            //进行判断,当前item对象是否是上传文件项
            if (item.isFormField()){
                //说明普通表单向
            }else {
                //说明上传文件项
                //获取上传文件的名称
                String filename = item.getName();
                //把文件的名称设置成唯一值,uuid
                String uuid = UUID.randomUUID().toString().replace("-", "");
                filename=uuid+"_"+filename;
                //完成文件上传
                item.write(new File(path,filename));
                //删除临时文件
                item.delete();
            }
        }
        return "success";
    }
}

2. SpringMVC实现文件上传

  • SpringMVC框架提供了MultipartFile对象,该对象表示上传的文件,要求变量名称必须和表单file标签的name属性名称相同。name="upload2"和MultipartFile upload2
  • springmvc.xml配置文件解析器对象如下:
<!--配置文件解析器对象,要求id名称必须是multipartResolver-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--配置上传文件的属性:大小:以字节为单位,下面配置10M-->
        <property name="maxUploadSize" value="10485760"></property>
    </bean>

index.jsp

<h3>SpringMVC文件上传</h3>
    <form action="user/fileupload2" method="post" enctype="multipart/form-data">
      选择文件:<input type="file" name="upload2"/><br>
      <input type="submit" value="上传">
    </form>


controller控制层

/**SpringMVC文件上传方式*/
@Controller
@RequestMapping(value = "/user")
public class FileUpload2 {
    @RequestMapping("/fileupload2")
    //upload2 必须与请求表单的一致
    public String fileupload1(HttpServletRequest request, MultipartFile upload2) throws Exception {
        System.out.println("SpringMVC文件上传:fileupload2文件上传。。");

        //使用fileupload组件完成文件上传
        //上传的位置,通过session获取ServletContext对象,再获取绝对路径
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //判断,该路径是否存在
        File file=new File(path);
        if (!file.exists()) {
            //创建文件夹
            file.mkdirs();
        }

        //说明上传文件项
        //获取上传文件的名称
        String filename = upload2.getOriginalFilename();
        //把文件的名称设置成唯一值,uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + "_" + filename;
        //完成文件上传
        upload2.transferTo(new File(path, filename));
        return "success";
    }
}

3. SpringMVC跨服务器方式文件上传


(1) 需要导入的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>

(2) 根据文档配置tomcat9的服务器,要配置2个服务器,一个作为上传服务器,一个作为图片接收服务器,端口号不能一样。
index.jsp

<h3>跨服务器文件上传</h3>
    <form action="user/fileupload3" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="upload3"/><br>
        <input type="submit" value="上传">
    </form>

controller层

/**SpringMVC文件跨服务器上传*/
@Controller
@RequestMapping(value = "/user")
public class FileUpload3 {
    @RequestMapping("/fileupload3")
    //upload2 必须与请求表单的一致
    public String fileupload1(MultipartFile upload3) throws Exception {
        System.out.println("跨服务器上传:fileupload3文件上传。。");

        //定义上传文件到的服务器路径,8086是图片服务器
        String path="http://localhost:8086/uploads/";
        //说明上传文件项
        //获取上传文件的名称
        String filename = upload3.getOriginalFilename();
        //把文件的名称设置成唯一值,uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + "_" + filename;

        //完成文件上传,跨服务器上传
        //创建客户端对象
        Client client = Client.create();
        //和图片服务器进行连接
        WebResource webresource = client.resource(path + filename);
        //上传文件
        webresource.put(upload3.getBytes());
        return "success";
    }
}

SpringMVC黑马:SpringMVC实现文件上传_第1张图片

你可能感兴趣的:(SpringMVC黑马:SpringMVC实现文件上传)