SpringBoot如何上传文件呢?

欣喜 SpringBoot 发布时间:2024-01-25 16:57:21 阅读数:10886 1
下文笔者讲述Springboot上传文件的方法及示例分享,如下所示
SpringBoot默认拥有文件上传的功能 
      我们只需接收相应的文件信息
      然后将文件保存在相应的磁盘位置即可

注意事项:
    Spring Boot上传文件有一些默认配置需修改,如下所示

spring:
  servlet:
    multipart:
      enabled: true   #是否处理上传
      max-file-size: 1MB   #允许最大的单个上传大小,单位可以是kb
      max-request-size: 10MB  #允许最大请求大小          
例:SpringBoot上传文件的示例
 
package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

@Controller
public class FileUploadController {


    /**
     * 因为最终项目会打成jar包,所以这个的路径不能是jar包里面的路径
     * 可以使用其他路径,比如上传到F盘下的upload文件夹下 写成:F:/upload/
     */
    private String fileUploadPath = "";

    /**
     * 文件上传,具体逻辑可以自行完善
     *
     * @param file 前端表单的name名
     * @return w
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) {

        if (file.isEmpty()) {
            //文件空了
            return null;
        }

        //文件扩展名
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        //使用UUID生成文件名称
        String fileName = UUID.randomUUID().toString() + extName;

        //文件上传的全路径
        String filePath = fileUploadPath + fileName;

        File toFile=new File(filePath);

        if (!toFile.getParentFile().exists()){
            //文件夹不存在,先创建文件夹
            toFile.getParentFile().mkdirs();
        }
        try {
            //进行文件复制上传
            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(toFile));
        } catch (Exception e) {
            //上传失败
            e.printStackTrace();
        }
        //返回文件所在绝对路径
        return filePath;

    }

}
 

然后添加个配置就可以把路径映射出去
 
@Configuration
public class webMvcConfigurerAdapter implements WebMvcConfigurer {
    /**
     * 配置静态访问资源
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/file/**").addResourceLocations("classpath:/path/");
    }
}
 
addResoureHandler:指的是对外暴露的访问路径
addResourceLocations:指的是内部文件放置的目录(如果在项目下 可以配置成    file:/path/)
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202401/7784.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者