SpringBoot文件上传,案例教学全教程

SpringBoot文件上传,案例教学全教程,第1张

创建Springboot项目,需要有spring-boot-starter-web支持就可以

     
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-tomcat
            provided
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

创建页面:




    
    单文件上传


创建控制器:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

/**
 * @Description
 * @Author Johnny
 */
@Controller
public class UploadController {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);
    
    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败,请选择文件";
        }
        String fileName = file.getOriginalFilename();
        String filePath = "d:/dir/";
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            LOGGER.info("上传成功");
            return "上传成功";
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        return "上传失败!";
    }
}

配置文件书写,这里默认可以不配置,不配置的话,就是不限制文件的大小

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

实现上传页面:

 上传完成:

 然后你去对应的磁盘路径中就能看到该文件。success

想要使用springboot项目,映射磁盘的某个地址的文件夹位置,从而访问该文件夹下的内容:

首先,创建一个配置类:自定义类,继承WebMvcConfigurerAdapter

重写里面的addResourceHandlers方法

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
 
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //文件磁盘图片url 映射
        //配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径
        registry.addResourceHandler("/dir/*").addResourceLocations("file:D:\dir\");

    }
}

第一个参数:是你需要映射的url访问的地址。

第二个参数:是你具体的物理磁盘路径地址。

最后实现访问:

 完成访问,恭喜你成功~

最后附上Gitee源码,提供给大家参考:

SpringBoot文件上传案例: SpringBoot文件上传案例https://gitee.com/vipzyj/spring-boot-file-upload-case.git如果对你有所帮助,请:点赞、留言。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/738505.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存