当前位置: 首页 > article >正文

springMVC实现文件上传

目录

一、创建项目

二、引入依赖

三、web.xml

四、编写上传文件的jsp页面

五、spring-mvc.xml

六、controller

七、运行


一、创建项目

二、引入依赖

<?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.qcby</groupId>
    <artifactId>springMVC15</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!--版本锁定-->
        <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>
    </dependencies>

</project>

三、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--配置解决中文乱码问题的过滤器-->
    <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>
    <!--前端控制器-->
    <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:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

四、编写上传文件的jsp页面

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2024/11/7
  Time: 21:50
  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="fileupload.do" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload" /><br/>
    <input type="submit" value="上传" />
</form>
</body>
</html>

五、spring-mvc.xml

spring-mvc.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">

    <!-- 配置spring创建容器时要扫描的包 -->
    <context:component-scan base-package="com.qcby"></context:component-scan>
    <!--配置视图解析器,进行页面的跳转-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--跳转的页面的路径-->
        <property name="prefix" value="/WEB-INF/pages/" />
        <!--跳转页面的后缀名称-->
        <property name="suffix" value=".jsp" />
    </bean>
    <!--配置文件上传的解析器组件。id的名称是固定,不能乱写-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--设置上传文件的总大小 8M = 8 * 1024 * 1024 -->
        <property name="maxUploadSize" value="8388608" />
    </bean>
    <!--让映射器、适配器和处理器生效(默认不配置也是可以的)-->
    <mvc:annotation-driven/>
</beans>

六、controller

UploadController类

package com.qcby.controller;

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.UUID;

@Controller
public class UploadController {
    @RequestMapping("/fileupload.do")
    public String upload(MultipartFile upload, HttpServletRequest request) throws IOException {
        // 把文件上传到哪个位置
        String realPath = request.getSession().getServletContext().getRealPath("/uploads");
        // 创建该文件夹
        File file = new File(realPath);
        // 判断该文件夹是否存在
        if(!file.exists()){
            // 创建文件夹
            file.mkdirs();
        }
        // 获取到上传文件的名称
        String filename = upload.getOriginalFilename();
        // 把文件的名称修改成为一的值 sdfs-csdf-fwer-sdfw
        String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        // 唯一的值
        filename = uuid+"_"+filename;
        System.out.println("文件名称:"+filename);
        // 上传文件
        upload.transferTo(new File(file,filename));
        return "success";
    }
}

七、运行

控制台:

uploads文件夹:

上传成功!


http://www.kler.cn/a/505238.html

相关文章:

  • 【C】初阶数据结构3 -- 单链表
  • 抢十八游戏
  • 美摄科技为企业打造专属PC端视频编辑私有化部署方案
  • dockerfile2.0
  • Kbengine+Unity3D多人在线游戏服务器+客户端从源码详细搭建教程
  • shell脚本回顾1
  • Java中的反射机制:动态操作类的秘密武器
  • PHP 字符串
  • doris:手动分区
  • ChatGPT正在朝着全面个人助手迈出重要一步,推出了一个名为“Tasks”的新功能
  • 防火墙配置的关键要素
  • 使用Redis防止重复发送RabbitMQ消息
  • C/C++新春烟花
  • UE_C++ —— UE反射系统
  • Quinlan C4.5剪枝U(0,6)U(1,16)等置信上限如何计算?
  • A4.Springboot-LLama3.2服务自动化构建(一)——构建docker镜像配置
  • 安装 MySQL 数据库
  • Java面试总结(1)
  • 迅翼SwiftWing | ROS 固定翼开源仿真平台正式发布!
  • 2Spark Core
  • 昇腾部署onnx模型问题总结
  • ubuntu18.04开发环境下samba服务器的搭建
  • Pcl联合Qt显示点云
  • EF Core执行原生SQL语句
  • Python爬虫实战:从抓取年报并分析数据开始
  • [leetcode]链表基础回顾