springMVC——文件上传

springMVC——文件上传

一、环境搭建

1、依赖
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring.version>5.0.2.RELEASE</spring.version>
</properties>
        <!--依赖坐标-->
<dependencies>
<!--spring核心依赖坐标-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>${spring.version}</version>
</dependency>
<!--spring支持web应用的依赖坐标-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>${spring.version}</version>
</dependency>
<!--springmvc依赖坐标-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>${spring.version}</version>
</dependency>
<!--支持servlet的依赖坐标-->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>servlet-api</artifactId>
  <version>2.5</version>
  <scope>provided</scope>
</dependency>
<!--支持jsp的依赖坐标-->
<dependency>
  <groupId>javax.servlet.jsp</groupId>
  <artifactId>jsp-api</artifactId>
  <version>2.0</version>
  <scope>provided</scope>
  <!--文件上传-->
</dependency>
  <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
  </dependency>
<!--跨服务器上传-->
  <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>
</dependencies>
2、web.xml
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--配置前端控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载springmvc.xml文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--启动的时候加载-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!--配置解决中文乱码的过滤器-->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encodeing</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
3、springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--释放静态资源-->
    <mvc:resources mapping="/sources/**" location="/sources/"></mvc:resources>

    <!--开启包扫描-->
    <context:component-scan base-package="com.xsl"/>

    <!--视图解析器对象-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--返回的页面的文件的目录所在-->
        <property name="prefix" value="/"></property>
        <!--后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--默认编码-->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!--文件上传最大值5MB,5*1024*1024-->
        <property name="maxUploadSize" value="5242880"></property>
    </bean>

    <!--开启springmvc框架的注解支持-->
    <mvc:annotation-driven></mvc:annotation-driven>

</beans>
4、创建静态资源目录

图片存储在sources文件目录下,所以需要在webapps下创建一个sources目录

二、前端页面

1、index.jsp
<%--
  Created by IntelliJ IDEA.
  User: xsl
  Date: 2019/12/2
  Time: 11:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
        <form method="post" action="upload/old" enctype="multipart/form-data">
            旧方式上传文件:<br/>
            选择文件:<input type="file" name="upload">  <br/>
            <input type="submit" value="上传">
        </form>
        <hr/>
        <form method="post" action="upload/springMVC" enctype="multipart/form-data">
            springMVC方式上传文件:<br/>
            选择文件:<input type="file" name="uploadSpringMVC">  <br/>
            <input type="submit" value="上传">
        </form>
        <hr/>
        <hr/>
        <form method="post" action="upload/step" enctype="multipart/form-data">
            跨服务器方式上传文件:<br/>
            选择文件:<input type="file" name="uploadSpringMVC">  <br/>
            <input type="submit" value="上传">
        </form>
</body>
</html>

2、success.jsp

<%--
  Created by IntelliJ IDEA.
  User: xsl
  Date: 2019/12/2
  Time: 11:55
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
上传成功!
</body>
</html>

三、controller

package com.xsl.controller;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UpLoadController {

    /**
     * 传统方式上传文件
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/old")
    public String uoloadOld(HttpServletRequest request) throws Exception {
        //获取当前绝对路径
        String sources = request.getSession().getServletContext().getRealPath("/sources/");
        //创建文件
        File file = new File(sources);
        if (!file.exists()){
           file.mkdirs();
        }
        //解析request对象,获取上传文件项
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
        List<FileItem> fileItems = upload.parseRequest(request);
        for (FileItem item:fileItems) {
            if (item.isFormField()){
                //普通表单项
            }else {
                //上传表单项
                String fileName = item.getName();
                String uuid = UUID.randomUUID().toString();
                item.write(new File(sources,uuid+"_"+fileName));
                item.delete();
            }
        }
        return "success";
    }

    /**
     * springMVC上传文件
     * @param request
     * @param uploadSpringMVC
     * @return
     * @throws IOException
     */
    @RequestMapping("/springMVC")
    public String uploadSpringMVC(HttpServletRequest request, MultipartFile uploadSpringMVC) throws IOException {
        //获取当前绝对路径
        String sources = request.getSession().getServletContext().getRealPath("/sources/");
        //创建文件
        File file = new File(sources);
        if (!file.exists()){
            file.mkdirs();
        }
        //获取文件名
        String originalFilename = uploadSpringMVC.getOriginalFilename();
        String uuid = UUID.randomUUID().toString();
        //上传
        uploadSpringMVC.transferTo(new File(sources,uuid+"_"+originalFilename));
        return "success";
    }
    /**
     * 跨服务器上传文件
     */
    @RequestMapping("/step")
    public String uploadStep(MultipartFile uploadSpringMVC) throws IOException {
        String path = "http://localhost:8081/sources/";
        String originalFilename = uploadSpringMVC.getOriginalFilename();
        //创建客户端
        Client client = Client.create();
        //和图片服务器连接
        WebResource resource = client.resource(path + originalFilename);
        resource.put(uploadSpringMVC.getBytes());
        return "success";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值