SpringMVC中文件上传的步骤代码举例以及文件上传的前台三要素

在 Spring MVC 中实现文件上传功能通常涉及以下步骤:

1. 添加依赖:确保项目中包含了处理文件上传所需的依赖,通常是 `commons-fileupload` 和 `commons-io`。

2. 配置Spring MVC:在 Spring MVC 配置中启用文件上传支持,并设置上传文件的最大大小限制。

3. 创建控制器:创建一个控制器,使用 `@RequestParam` 来接收上传的文件,并使用`MultipartFile` 类型的参数来访问文件数据。

4. 处理文件:在控制器的方法中处理接收到的文件,例如保存到服务器的文件系统或数据库中。

下面是一个简单的文件上传的代码示例:

① 添加依赖

在 `pom.xml` 中添加 `commons-fileupload` 和 `commons-io` 依赖:

<dependencies>
    <!-- 其他依赖 -->

    <!-- 文件上传依赖 -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.8.0</version>
    </dependency>
</dependencies>

②配置Spring MVC

在 Spring MVC 配置类中配置文件上传的最大大小限制:

配置文件上传解析器,springmvc 的配置文件的文件上传解析器的 id 属性必须为 multipartResolver
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setMaxUploadSize(1024 * 1024 * 10); // 设置最大上传大小为10MB
        return resolver;
    }
}

③创建控制器

创建一个控制器来处理文件上传请求:

后端对应的接收文件的方法参数类型必须为 MultipartFile,参数名称必须与前端的 name 属性保持一致
@Controller
public class FileUploadController {

    // 定义一个处理文件上传的方法
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // 获取文件名
                String fileName = file.getOriginalFilename();
                // 保存文件到服务器的路径
                Path targetLocation = Paths.get("uploads").resolve(fileName);
                Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
                
                // 返回上传成功信息
                return "redirect:/uploadSuccess";
            } catch (IOException ex) {
                // 处理可能的 I/O 异常
                ex.printStackTrace();
            }
        }
        // 返回上传失败信息
        return "redirect:/uploadError";
    }
}

④创建视图

创建两个简单的视图页面来展示上传成功和失败的信息:uploadSuccess.jsp:

<!DOCTYPE html>
<html>
<head>
    <title>Upload Success</title>
</head>
<body>
    <h2>File uploaded successfully!</h2>
</body>
</html>

文件上传的前台三要素:

        ①form 表单的提交方式必须为 post

        ②enctype 属性需要修改为:multipart/form-data

        ③input 标签必须有一个 type 属性为 file 的,其中需要有一个 name 属性;如果需要 上传多个文件需要添加 multiple 属性

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值