SpringBoot 实现文件上传,图片上传并显示功能

大家好,我是小朔哥,今天为大家分享的是spring boot实现文件上传。

SpringBoot 实现文件上传,图片上传并显示功能

我先看一下《颈椎病康复指南》再给大家说怎么实现的这两个功能,毕竟只是一个新手,解决这种复杂点的问题(相对而言),还是需要花费大量时间的,这篇文章花了两天的时间才实现的功能,现在就记录一下使用springboot怎么实现文件上传下载的。

SpringBoot 实现文件上传,图片上传并显示功能

不仅仅看《颈椎病康复指南》还有图片这些。

我这里使用的是 springboot 2.0.3,不需要导入相关jar包,2.x 的版本已经整合进去了,直接使用即可。

spring官网提供了 springboot 的文件上传下载案例,这是网址:https://spring.io/guides/gs/uploading-files/,使用的是流的输出,对于我这个新手来说,直接不理解,所以略过,通过网上查阅大量资料,终于把问题解决了。下面的案例是 springboot2.x 图片上传与回显。我使用的工具是idea。

1、创建idea默认的springboot项目,我的版本是2.0.3

2、创建一个控制层FileController

package com.rainy.controller;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;
/**
* 文件上传
*/
@Controller
public class FileController {
@GetMapping(value = "/file")
public String file() {
return "file";
}
@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 = "D://temp-rainy//"; // 上传后的路径
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 = "/temp-rainy/" + fileName;
model.addAttribute("filename", filename);
return "file";
}
}

3、创建MyWebMvcConfigurer,这里是配置资源映射路径,详细点的介绍看这篇文章:https://blog.csdn.net/qq_38762237/article/details/81283241

/**
* 资源映射路径
*/
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/temp-rainy/**").addResourceLocations("file:D:/temp-rainy/");
}
}

4、jsp页面




<title>Title/<title>







注意一点:我是使用jsp引擎来渲染,因为我不会用 Thymeleaf,添加jsp页面,springboot使用jsp页面是需要进行配置jsp整合的,默认的是 Thymeleaf 的页面,简单的就是HTML页面

springboot配置jsp页面的方法:https://blog.csdn.net/qq_38762237/article/details/81283352

大家平时不知道有没有遇到springboot相关的问题,作者在这里为大家总结了一个spring boot学习技术路线,包括整个微服务:

SpringBoot 实现文件上传,图片上传并显示功能

欢迎做Java的工程师朋友们私信我【Java】免费获取这个思维导图,还有更多免费的Java架构学习资料,还有BAT大厂架构师技术知识导图和相关的技术分享视频,希望可以帮助大家扩展自己的技术广度和知识面。

领取的朋友们记得一定要帮作者来个转发+评论!谢谢大家!

转发+评论后私信【Java】就能免费获取领取方式了


分享到:


相關文章: