最近,做一个案例,需要实现图片的上传,和回显,
逻辑思想:前端页面上传图片资源 到 服务器自定义的文件夹, 然后把上传的路径写进数据库,查询数据库进行回显。
如果上传的图片到服务器自定义的文件夹里,然后进行回显, 则需要把该文件夹 配置成springboot 资源文件
下面是普通回显,不涉及数据库。
1,前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>upload</title>
</head>
<body>
<h1>文件上传</h1> <!--上传格式-->
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" ><br>
<input type="submit">
</form>
</body>
</html>
回显图片html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>lookp</title>
</head>
<body>
<img th:src="${path}" style="width: 300px; height: 300px;">
</body>
</html>
springboot后端代码
package cn.lczze.lovenet.controller;
import cn.lczze.lovenet.service.indexService;
import cn.lczze.lovenet.utils.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
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 org.springframework.web.servlet.ModelAndView;
import java.io.File;
import java.io.IOException;
/**
* Created by lczze on 2020/11/10 9:45
*/
@Controller
public class indexController {
Logger logger = LoggerFactory.getLogger(indexController.class);
@ResponseBody
@PostMapping("/upload")
public ModelAndView upload(@RequestParam("file")MultipartFile file) throws IOException {
ModelAndView mv = new ModelAndView();
if(!file.isEmpty()) {
String filename = file.getOriginalFilename();
//上传路径 服务器自定义路径
String filepath = "/lczze/net/image/";
//上传路径 + 文件名
File dest = new File(filepath +filename);
//文件上传
file.transferTo(dest);
logger.info("文件上传成功啦----------"+filepath + RandomS+filename );
//测试回显路径
String path01 = "http://服务器地址:8083/img/"+filename;
logger.warn(path01+"----回显图片地址----------");
mv.addObject("path" ,path01);
mv.setViewName("lookphoto");
return mv;
}else{
logger.info("文件上传失败----------");
mv.setViewName("upload");
return mv;
}
}
}
配置资源文件
#上传中文件的大小
spring.servlet.multipart.max-request-size=10MB
#单个文件的大小
spring.servlet.multipart.file-size-threshold=10MB
# 设置当URI为/img/**时,才进过静态资源
# 注:如果设置为/**,那么表示任何访问都会经过静态资源路径
spring.mvc.static-path-pattern=/img/**
# spring 静态资源扫描路径
spring.resources.static-locations=classpath:/static/,file:/lczze/net/image/
上传效果:
上传成功
回显成功
注意访问路径 切记 加img
切记 加img ,避免采坑
如有问题可以加 技术交流QQ群 922850187 进行答疑
最后艾特一下我的 个人博客网站 IT大咖之家
加油,打工人…