Springboot上传文件

本文详细介绍了使用SpringBoot进行文件上传的全过程,包括所需依赖、配置及代码实现。通过实例展示了如何设置上传文件的大小限制,以及如何处理上传的文件并返回响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.导入依赖

其实上传文件不要啥依赖,你把springbootweb启动器导入就好。

<!--json-->
		<!--json工具-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
  
        <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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

2.编写配置

2.X以上得springboot

## 上传文件总的最大值
spring.servlet.multipart.max-request-size: 30MB
## 单个文件的最大值
spring.servlet.multipart.max-file-size: 10MB

2.X以下得springboot

## 上传文件总的最大值
spring.servlet.multipart.maxrequestsize: 30MB
## 单个文件的最大值
spring.servlet.multipart.maxfilesize: 10MB

3.编写代码

package com.fwwb.controller;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
public class UploadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    /**
     * 上传文件
     * @param file 数据文件
     * @param response
     */
    @PostMapping("/upload")
    public void upload(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        JSONObject json = new JSONObject();
        if (file.isEmpty()) {
            json.put("msg","上传失败,请选择文件");
        }else{
            String fileName = file.getOriginalFilename();
            //这里可以判断后缀是否符合
            String suffix = fileName.substring(fileName.indexOf('.')+1); //后缀
            fileName = fileName.substring(0,fileName.indexOf('.'))+"_"+randownName(); //新文件名
//        String filePath = "/workspace/temp";
			//这个是本地测试的filePath
            String filePath = "D:\\workspace";
            File dest = new File(filePath);
            //创建文件保存地址
            if(!dest.exists()){
                dest.mkdirs();
            }
            File excelFile = new File(filePath + "/" +fileName + "." +suffix);
            System.out.println(excelFile);

            PrintWriter out = null;
            try {
                out = response.getWriter();
                file.transferTo(excelFile);
                json.put("msg","上传成功");
            } catch (IOException e) {
                LOGGER.error(e.toString(), e);
                json.put("msg","上传失败");
            }
            char[] buf = json.toString().toCharArray();
            if(buf.length>0){
                out.write(buf);//发送
                out.flush();
                out.close();
            }
        }

        try {
            response.getWriter().print(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成16位随机字符串
     * @return
     */
    private static String randownName() {
        String str = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz";
        StringBuffer res = new StringBuffer("");
        for (int i = 0; i < 12; i++) {
            res.append(str.charAt((int) (Math.random() * str.length() - 1)));
        }
        return res.toString();
    }
}

参考代码:https://blog.youkuaiyun.com/gnail_oug/article/details/80324120

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值