使用SpringBoot的MultipartFile完成文件上传功能

前端:

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="http://localhost:9090/upload" method="post"  enctype="multipart/form-data">
    <input name="file"  type="file">

    <input type="submit" value="提交">

</form>

</body>
</html>

后端:

添加依赖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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置文件:

application.yaml:

server:
  port: 9090
spring:
  servlet:
    multipart:
      # 文件上传的最大值
      max-file-size: 100MB
      # 文件请求的最大值
      max-request-size: 100MB

控制层:

package com.xiaozhuang.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileController {
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String,Object>> fileUploadHandler(MultipartFile file){
        // 创建一个Map对象,用于存储返回的数据
        Map<String, Object> map = new HashMap<>();
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        System.out.println("上传的文件名称"+originalFilename);
        // 定义文件保存的目录路径
        String savePath = "D:/upload";
        // 确保目录存在,如果不存在则创建
        File directory = new File(savePath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        // 确定文件保存的完整路径
        String filePath = savePath + File.separator + originalFilename;
        // 将文件保存到指定路径
        try {
            file.transferTo(new File(filePath));
            map.put("message", "文件上传成功");
        } catch (IOException e) {
            map.put("error", "文件上传失败: " + e.getMessage());
        }
        // 返回一个ResponseEntity对象,包含map和HTTP状态码HttpStatus.ACCEPTED
        return new ResponseEntity<>(map, HttpStatus.ACCEPTED);
    }
}

跨域问题解决:

package com.xiaozhuang.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CrosConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowCredentials(false)
                        .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                        .allowedOrigins("*");
            }
        };
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值