文章目录
0、共公部分
0.1 项目结构
0.2 pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gh</groupId>
<artifactId>thymeleafPictureDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>thymeleafPictureDemo</name>
<description>springboot结合thymeleaf上传图片、删除图片,服务器和本地</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
0.3 application.yml文件
server:
port: 9098
spring:
mvc:
# 访问静态资源地址
static-path-pattern: /static/**
web:
resources:
# 设置静态资源包的路径
static-locations: classpath:/static
0.4 controller文件
0.4.1 imageUploadController
package com.gh.thymeleafPictureDemo.controller;
import com.gh.thymeleafPictureDemo.util.Result;
import com.gh.thymeleafPictureDemo.util.UploadImageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* 图片上传
* @author gh
* @date 2020/12/5
*/
@CrossOrigin("*")
@RestController
@RequestMapping("/api")
@Slf4j
public class imageUploadController {
/**
* 上传图片测试
* @return
*/
@RequestMapping("/upload")
public Result<String> uploadImage(MultipartFile file){
Result result = new Result<>();
result.setCode(1);
result.setData("数据");
String imagePath = UploadImageUtil.uploadImage(file);
if(imagePath.length() > 0){
result.setMsg(imagePath);
return result;
}
result.setMsg("上传失败");
return result;
}
/**
* 删除图片
* @param path
* @return
*/
@RequestMapping("/deleteFile")
public Result<String> uploadImage(String path){
Result result = new Result<>();
result.setCode(1);
result.setData("数据");
log.info("图片路径" + path);
if(UploadImageUtil.deleteImage(path)){
result.setMsg("删除成功");
return result;
}
result.setMsg("删除失败");
return result;
}
}
0.4.2 pageController
package com.gh.thymeleafPictureDemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author gh
* @date 2020/12/6
*/
@Controller
public class pageController {
/**
* thymeleaf跳转到image.html页面
* @return 界面
*/
@RequestMapping("/")
public String mixPage(){
return "image";
}
}
0.5 部分uitl文件
0.5.1 FileUtil
package com.gh.thymeleafPictureDemo.util;
import java.io.File;
import java.io.FileOutputStream;
/**
* @author gh
* @date 2020/12/5
*/
public class FileUtil {
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath + fileName);
out.write(file);
out.flush();
out.close();
}
}
0.5.2 ImageUtil
package com.gh.thymeleafPictureDemo.util;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
/**
* 图片上传需要,将图片转换
* @author gh
* @date 2020/11/25
*/
public class ImageUtil {
public static BufferedImage change2jpg(File f) {
try {
Image i = Toolkit.getDefaultToolkit().createImage(f.getAbsolutePath());
PixelGrabber pg = new PixelGrabber(i, 0, 0, -1, -1, true);
pg.grabPixels();
int width = pg.getWidth(), height = pg.getHeight();
final int[] RGB_MASKS = { 0xFF0000, 0xFF00, 0xFF };
final ColorModel RGB_OPAQUE = new DirectColorModel(32, RGB_MASKS[0], RGB_MASKS[1], RGB_MASKS[2]);
DataBuffer buffer = new DataBufferInt((int[]) pg.getPixels(), pg.getWidth() * pg.getHeight());
WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, RGB_MASKS, null);
BufferedImage img = new BufferedImage(RGB_OPAQUE, raster, false, null);
return img;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public static void resizeImage(File srcFile, int width,int height, File destFile) {
try {
if(!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
Image i = ImageIO.read(srcFile);
i = resizeImage(i, width, height);
ImageIO.write((RenderedImage) i, "jpg", destFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Image resizeImage(Image srcImage, int width, int height) {
try {
BufferedImage buffImg = null;
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
buffImg.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
return buffImg;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
0.5.3 Result
package com.gh.thymeleafPictureDemo.util;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 通用接口返回类型,这里不仅仅可以用T
* 随便用什么都可以的
* @author gh
* @date 2020/11/19
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> implements Serializable {
int code;
T data;
String msg;
private static final long serialVersionUID = 1L;
}
1、原图上传
其实就是UploadImageUtil不同而已
1.1 本地上传
这里因为要放在target目录下,所以本地和服务器不能用同一个函数,,,这里可能还有解决办法,但是我暂时没有找到,如果有老哥可以找到可以讨论一下,嘿嘿
/**
* 删除图片函数,本地用
* @param imagePath 这个是图片名字的完整路径
* @return 结果
*/
public static boolean deleteImage(String imagePath){
try {
imagePath = URLDecoder.decode((ResourceUtils.getURL("classpath:").getPath()) + imagePath, System.getProperty("file.encoding"));
File file = new File(imagePath);
log.info("删除图片");
log.info(imagePath);
// 删除图片
file.delete();
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
/**
* 上传图片函数,本地用
* @param file 图片文件
* @return
*/
public static String uploadImage(MultipartFile file){
// 获取唯一的uuid
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
try {
String filePath = URLDecoder.decode((ResourceUtils.getURL("classpath:").getPath()+"static/img/"), System.getProperty("file.encoding"));
FileUtil.uploadFile(file.getBytes(), filePath, uuid + ".jpg");
log.info("上传图片");
log.info(filePath + uuid + ".jpg");
return "/static/img/" + uuid + ".jpg";
} catch (Exception e) {
// 上传失败
return "";
}
}
1.2 上传到服务器
这里要注意,因为用了nginx反向代理,所以,访问的时候要配置静态资源访问
nginx配置伪静态,这样就能访问到image目录下的图片了
/**
* 上传图片函数,服务器用的
* @param file 图片文件
* @return
*/
public static String uploadImage(MultipartFile file){
// 获取唯一的uuid
// String filePath = URLDecoder.decode(Objects.requireNonNull(Objects.requireNonNull(ClassUtils.getDefaultClassLoader()).getResource("")).getPath()) + "static/img/";
String filePath = "image/";
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
log.info("图片路径" + filePath);
try {
FileUtil.uploadFile(file.getBytes(), filePath, uuid + ".jpg");
log.info("上传图片");
log.info(filePath + uuid + ".jpg");
return "/" + filePath + uuid + ".jpg";
} catch (Exception e) {
// 上传失败
return "";
}
}
/**
* 删除图片函数,服务器用的
* @param imagePath 这个是图片名字的完整路径
* @return 结果
*/
public static boolean deleteImage(String imagePath){
try {
// 去除第一个字符串,不然服务器哪里删除不了图片
imagePath = imagePath.substring(1);
File file = new File(imagePath);
log.info("删除图片");
log.info(imagePath);
// 删除图片
file.delete();
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
2、压缩上传
这里主要是靠ImageUtil文件,但是这个文件我是在网上找的,发现有些图片会失真,,,但是大部分还是有用的
2.1 本地上传
/**
* 删除图片函数,本地用
* @param imagePath 这个是图片名字的完整路径
* @return 结果
*/
public static boolean deleteImage(String imagePath){
try {
log.info("删除图片");
log.info(imagePath);
imagePath = URLDecoder.decode((ResourceUtils.getURL("classpath:").getPath()) + imagePath, System.getProperty("file.encoding"));
File file = new File(imagePath);
// 删除图片
file.delete();
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
/**
* 上传图片函数,本地用
* @param file 图片文件
* @return 结果
*/
public static String uploadImage(MultipartFile file){
// 获取唯一的uuid
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
try {
// 获取图片存储的完整路径
String path1 = URLDecoder.decode((ResourceUtils.getURL("classpath:").getPath()+"static/img/"), System.getProperty("file.encoding"));
String imagePath = path1 + uuid + ".jpg";
log.info("上传图片");
log.info(imagePath);
// 获取要上传图片的目录,同时解码
File imageFolder = new File(URLDecoder.decode(path1, System.getProperty("file.encoding")));
if(!imageFolder.exists()){
// 先检查这个目录是否存在
imageFolder.mkdirs();
}
// new一个图片文件
File fileImage = new File(imageFolder, uuid + ".jpg");
if (!fileImage.isFile()) {
// 如果不存在这个文件
fileImage.createNewFile();
}
FileUtils.copyInputStreamToFile(file.getInputStream(), fileImage);
BufferedImage img = ImageUtil.change2jpg(fileImage);
ImageIO.write(img, "jpg", fileImage);
// 返回图片的相对路径
return "/static/img/" + uuid + ".jpg";
}catch (Exception e){
e.printStackTrace();
// 上传图片失败就返回一个长度为0的空字符串
return "";
}
}
2.2 上传图片到服务器
和上面一样要配置nginx静态资源
/**
* 上传图片函数,服务器用的
* @param file 图片文件
* @return
*/
public static String uploadImage(MultipartFile file){
// 获取唯一的uuid
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
try {
// 获取图片存储的完整路径
String path1 = "image/";
String imagePath = path1 + uuid + ".jpg";
log.info("上传图片");
log.info(imagePath);
// 获取要上传图片的目录,同时解码
File imageFolder = new File(URLDecoder.decode(path1, System.getProperty("file.encoding")));
if(!imageFolder.exists()){
// 先检查这个目录是否存在
imageFolder.mkdirs();
}
// new一个图片文件
File fileImage = new File(imageFolder, uuid + ".jpg");
if (!fileImage.isFile()) {
// 如果不存在这个文件
fileImage.createNewFile();
}
FileUtils.copyInputStreamToFile(file.getInputStream(), fileImage);
BufferedImage img = ImageUtil.change2jpg(fileImage);
ImageIO.write(img, "jpg", fileImage);
// 返回图片的相对路径
return "/image/" + uuid + ".jpg";
}catch (Exception e){
e.printStackTrace();
// 上传图片失败就返回一个长度为0的空字符串
return "";
}
}
/**
* 删除图片函数,服务器用的
* @param imagePath 这个是图片名字的完整路径
* @return 结果
*/
public static boolean deleteImage(String imagePath){
try {
imagePath = imagePath.substring(1);
log.info("删除图片");
log.info(imagePath);
File file = new File(imagePath);
// 删除图片
file.delete();
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
如果觉得有用,各位观众老爷点个赞再走哈~谢谢(其实再加个关注也不介意哈哈哈)