SpringMVC实现三种文件上传的方式

加油,新时代打工人!

更多Spring MVC 参考
Spring MVC详细环境配置和入门
Spring MVC 响应数据和结果视图
文件上传分为三种方式

  1. 传统文件上传
  2. springmvc方式上传
  3. 跨服务器方式上传

项目目录

客户端文件上传项目名:springmvc_day02_02_fileupload
文件服务器项目名:springmvc_day02_fileserver

在这里插入图片描述

springmvc_day02_fileserver 项目

文件服务器只需要配好tomcat和客户端项目端口不冲突即可

springmvc_day02_02_fileupload

1.pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.itboy</groupId>
  <artifactId>springmvc_day02_02_fileupload</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>springmvc_day02_02_fileupload Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <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>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
      <!--文件上传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>
    <!--跨服务器文件上传-->
    <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>

  <build>
    <finalName>springmvc_day02_02_fileupload</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

2.index.jsp

<%--
  Created by IntelliJ IDEA.
  User: 儒雅
  Date: 2021/11/15
  Time: 9:20
  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>
<h3>传统方式文件上传</h3>
<form action="user/fileupload01" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload"/></br>
    <input type="submit" value="上传文件"/>
</form>
<h3>springmvc文件上传</h3>
<form action="user/fileupload02" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload"/></br>
    <input type="submit" value="上传文件"/>
</form>
<h3>跨服务器文件上传</h3>
<form action="user/fileupload03" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload"/></br>
    <input type="submit" value="上传文件"/>
</form>

</body>
</html>

3.resources下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">

    <!--开启注解扫描-->
    <context:component-scan base-package="com.itboy"></context:component-scan>

    <!--视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

  <!-- 配置文件解析器对象,要求id名称必须是multipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
       <!--配置上传文件大小10MB*1024*1024-->
        <property name="maxUploadSize" value="10485760"/>
    </bean>
      <!--开启注解支持-->
    <mvc:annotation-driven ></mvc:annotation-driven>
</beans>

4.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>
    <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>encoding</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>

5.webapp>WEB-INF>pages下success.jsp

<%--
  Created by IntelliJ IDEA.
  User: 儒雅
  Date: 2021/11/15
  Time: 9:24
  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>
<h3>上传成功</h3>
</body>
</html>

6.Usercontroller

package com.itboy.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.util.List;
import java.util.UUID;

/**
 * @author wh
 * @date 2021年11月15日9:26
 */
@RequestMapping("/user")
@Controller
public class Usercontroller {
    /**
     * 跨服务器方式上传文件
     * @param upload
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileupload03")
    private String fileupload03( MultipartFile upload) throws Exception {
        System.out.println("跨服务器文件上传已执行");
        String path="http://localhost:8089/springmvc_day02_fileserver/uploads/";
        String name = upload.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        name = uuid + "_" + name;
        Client client = Client.create();
        WebResource webResource = client.resource(path + name);
        webResource.put(upload.getBytes());
        return "success";
    }
    /**
     * spring MVC方式文件上传
     *
     * @param request
     * @param upload
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileupload02")
    private String fileupload02(HttpServletRequest request, MultipartFile upload) throws Exception {
        System.out.println("spring MVC方式文件上传已执行");
        String path = request.getSession().getServletContext().getRealPath("/uploads");
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        String name = upload.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        name = uuid + "_" + name;
        upload.transferTo(new File(path, name));

        return "success";
    }

    /**
     * 传统方式文件上传
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileupload01")
    private String fileupload01(HttpServletRequest request) throws Exception {
        System.out.println("传统方式文件上传已执行");
        String path = request.getSession().getServletContext().getRealPath("/uploads").toUpperCase();
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUplod = new ServletFileUpload(factory);
        List<FileItem> fileItems = fileUplod.parseRequest(request);
        for (FileItem items : fileItems) {
            if (items.isFormField()) {

            } else {
                String uuid = UUID.randomUUID().toString().replace("-", "");
                String name = items.getName();
                name = uuid + "_" + name;
                items.write(new File(path, name));
                items.delete();
            }
        }
        return "success";
    }
}

7.运行结果

在这里插入图片描述

springMVC文件上传原理

在这里插入图片描述

跨服务器文件上传原理

当客户去上传文件时,首先通过应用服务器,应用服务器去把图片put上到图片服务器上,然后保存图片成功到指定的路径中

在这里插入图片描述

遇到问题解决方案

异常1

消息 Request processing failed; nested exception is com.sun.jersey.api.client.UniformInterfaceException: PUT http://localhost:8089/springmvc_day02_fileserver/uploads/2EBF85554DE94462BD6B11247888F085_admin-login-bg1.jpg returned a response status of 405 Method Not Allowed
在这里插入图片描述
405 这个问题是因为tomcat默认不支持put上传的,需要在所在tomcat,在webapp下web.xml中的默认tomcat配置添加一段代码,不要找错了哦,第一个默认是php配置

		<init-param>
            <param-name>readonly</param-name>
            <param-value>false</param-value>
        </init-param>

截图
在这里插入图片描述

异常2

解决:这个问题是因为只开启了一个tomcat,配置的两个服务器都需要开启

消息 Request processing failed; nested exception is com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused: connect
在这里插入图片描述

异常3

409这个错误遇到的话,因为在文件项目所在的springmvc_day02_fileserver\target\springmvc_day02_fileserver路径下没有创建文件夹uploads

github项目源码地址

springmvc_day02_02_fileupload:https://github.com/itboywh/springmvc_day02_02_fileupload
springmvc_day02_fileserver:
https://github.com/itboywh/springmvc_day02_fileserver

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hello World呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值