springboot中文件上传到本地

文件上传的业务是我们经常遇到的,那么在spring中该怎么处理这个业务呢?

文件上传三个基础

  • <input type="file" name="image">
  • enctype="multipart/form-data" 这里必须是这个类型,否则上传不了,默认的是application/x-www-form-urlencoded只能上传文本格式的文件。不能用于发送文件
  • action="/api/upload" method="post"
html 复制代码
<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>Hello World</title>
</head>
<body>
   <form action="/api/upload" method="post" enctype="multipart/form-data">
       <input type="text" name="name">
       <input type="text" name="age">
       <input type="file" name="image">
       <input type="submit" value="Submit">
   </form>
</body>
</html>

接口处理

java 复制代码
package com.itheima.controller;


import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {


    @PostMapping
    public Result upload(String name, Integer age, MultipartFile image) throws Exception {
        log.info("文件上传成功 {},{},{}",name,age,image);
        String originalFilename = image.getOriginalFilename();
        image.transferTo(new File("D:\\360Downloads\\"+originalFilename));
        return Result.success();
    }

}

这样,我们就能在D:\360Downloads中看到上传的文件了



文件名优化

如果我们直接使用上传的文件名,会导致同名的被覆盖,造成文件的丢失

java 复制代码
@PostMapping
    public Result upload(String name, Integer age, MultipartFile image) throws Exception {
        log.info("文件上传成功 {},{},{}",name,age,image);

        String originalFilename = image.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String filename = UUID.randomUUID().toString() + extname;
        image.transferTo(new File("D:\\360Downloads\\"+filename));
        return Result.success();
}
java 复制代码
# 配置单个文件上传大小限制
spring.servlet.multipart.max-file-size=10MB

# 配置单个请求最大大小的限制,一次请求中是可以上传多个文件
spring.servlet.multipart.max-request-size=100MB
相关推荐
勤奋的知更鸟几秒前
Java编程之组合模式
java·开发语言·设计模式·组合模式
千|寻1 分钟前
【画江湖】langchain4j - Java1.8下spring boot集成ollama调用本地大模型之问道系列(第一问)
java·spring boot·后端·langchain
爱编程的喵15 分钟前
深入理解JavaScript原型机制:从Java到JS的面向对象编程之路
java·前端·javascript
on the way 12326 分钟前
行为型设计模式之Mediator(中介者)
java·设计模式·中介者模式
保持学习ing28 分钟前
Spring注解开发
java·深度学习·spring·框架
techzhi29 分钟前
SeaweedFS S3 Spring Boot Starter
java·spring boot·后端
酷爱码33 分钟前
Spring Boot 整合 Apache Flink 的详细过程
spring boot·flink·apache
异常君1 小时前
Spring 中的 FactoryBean 与 BeanFactory:核心概念深度解析
java·spring·面试
weixin_461259411 小时前
[C]C语言日志系统宏技巧解析
java·服务器·c语言
cacyiol_Z1 小时前
在SpringBoot中使用AWS SDK实现邮箱验证码服务
java·spring boot·spring