在SpringBoot中实现文件上传

        1.创建一个SpringBoot的项目,需要导入spring-boot-starter-web的依赖

         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        2.编写文件的核心配置application.properties

server.port=2100
#文件的保存地址
file-save-path=D:/a/f/picture/

#是否开启文件上传支持,默认为true。
spring.servlet.multipart.enabled=true 
#文件写入磁盘的阈值,默认为0。
spring.servlet.multipart.file-size-threshold=0
#上传文件的临时保存位置。
spring.servlet.multipart.location=D:/1javaweb/b
#上传的单个文件的最大大小,默认为1MB。
spring.servlet.multipart.max-file-size=30MB
#多文件上传时文件的总大小,默认为10MB。
spring.servlet.multipart.max-request-size=10MB
#文件是否延迟解析,默认为false。
spring.servlet.multipart.resolve-lazily=false

        3.编写控制层

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@RestController
public class FileUploadController {
    @Value("${file-save-path}")
    private String fileSavePath;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd/");

    @RequestMapping("/upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest req) {
        String filePath = "";
        String format = sdf.format(new Date());
        File folder = new File(fileSavePath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
            String oldName = uploadFile.getOriginalFilename();
            String newName = UUID.randomUUID().toString() +
                    oldName.substring(oldName.lastIndexOf("."), oldName.length());
            try {
                uploadFile.transferTo(new File(folder, newName));
                filePath = req.getScheme() + "://" + req.getServerName() + ":" +
                        req.getServerPort() + "/uploadFile/" + format + newName;
            } catch (IOException e) {
                return "上传失败! ";
            }
        }
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString().replace("-","") +
                oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            uploadFile.transferTo(new File(folder, newName));
            filePath = req.getScheme() + "://" + req.getServerName() + ":" +
                    req.getServerPort() + "/uploadFile/" + format + newName;
        } catch (IOException e) {
            return "上传失败! ";
        }
        return filePath;
    }
}

        4.在resources下创建static目录,然后创建update.html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title></head>
<body>
    <!--enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。-->
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="uploadFile" value="请选择文件" required>
    <input type="submit" value="上传">
</form>
</body>
</html>

        5.如果想要在缓存中查询刚刚上传的文件或图片,需要添加以下配置类

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${file-save-path}")
    private String fileSavePath;
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/uploadFile/**")
                .addResourceLocations("file:"+fileSavePath);
    }
}

        6.如果想要任何ip都能访问,需要添加以下配置类

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 CarsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")//所有的都配置跨域
                .allowedOrigins("*")//所有的请求可以访问跨域的资源
                 .allowedHeaders("*")//所有的请求头都可以访问
        .allowedMethods("GET","POST","PUT","DELETE","HEAD","OPTION")//什么类型的请求都可以访问后端资源
         .maxAge(3600)//服务端存储相关信息的时间      秒
        ;
    }
}

        7.启动我们的SpringBoot项目,访问该地址

http://localhost:2100/update.html

         如果我们配置了刚刚的WebConfig配置类,上传后的这个地址我们可以直接在浏览器进行访问,就可以看到我们刚刚上传的图片

         如果配置了跨域访问,则可以通过我们的ip访问,在别的计算机上也可以访问

查询本机计算机的ip: 

       1. 快捷键: win+r,在弹出的窗口输入cmd后点击确定

         2.输入

ipconfig

        找到自己电脑在当前局域网下的ip

 

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值