SpringBoot项目图片上传-01,并返回项目中图片路径

这篇博客介绍了如何使用SpringBoot进行文件上传,包括在pom.xml中添加依赖,创建form表单进行文件选择和提交,设置application.properties以指定文件存储路径,以及编写Controller处理文件上传请求。此外,还展示了如何配置WebMvcConfigurer以映射静态资源,确保图片可以被正确访问。同时,文中提到原先使用绝对路径的局限性,并提供了一个工具类来获取运行时的项目路径,以实现跨环境的文件存储。

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

Springboot官网在这里:https://spring.io/guides/gs/uploading-files/

需要使用的jar包

<dependencies>
		<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>

form表单发送请求存储图片

<form action="http://localhost:8080/file/fileUpload" method="post" enctype="multipart/form-data">
        <label>上传图片</label>
        <input type="file" name="file"/>
        <input type="submit" value="上传"/>
    </form>

文件上传,必须使用enctype="multipart/form-data",定义多部件的媒体文件

application.properties添加固定存储路径。以及文件访问路径格式

filepath=D:……/src/main/resources/static/images/

然后是controller代码

import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${filepath}")
    private String path;

    @PostMapping(value = "/fileUpload")
    public String fileUpload(@RequestParam(value = "file") MultipartFile file, Model model, HttpServletRequest request) {
        if (file.isEmpty()) {
            System.out.println("文件为空");
        }

        String fileName = file.getOriginalFilename(); // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = path; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filename = path + fileName;
        model.addAttribute("filename", filename);
        String requestURL = request.getRequestURL().toString();
        String requestURI = request.getRequestURI();
        System.out.println("requestURL"+requestURL);
        System.out.println("requestURI"+requestURI);
        return filename;
    }
}

添加资源映射路径

 @Value("${filepath}")
    private String path;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations(path);
    }
}

映射是必须的,他是主机地址和网络地址相互转换的关键。

更新

上面直接给出绝对路径只能在本机运行,换一台机子,就会找不到这个路径,
更新使用动态获取当前运行路径,并放在项目目录/static/images文件下

  1. 添加一个工具类,用来获取当前工作路径.调用此方法,获取运行时路径
import org.springframework.util.ResourceUtils;
import java.io.FileNotFoundException;
public class GetPath {
    static public String getPath() throws FileNotFoundException {
        return     ResourceUtils.getURL("src/main/resources/static/images").getPath();
    }
  1. FileController和映射配置获取此path
String filePath = GetPath.getPath();

注:此方法会抛出异常,使用时捕捉或抛出都可

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值