<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
spring:
thymeleaf:
# 页面目录
prefix: classpath:/templates/
# 后缀名
suffix: .html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>upload-imgtitle>
head>
<body>
<form enctype="multipart/form-data" method="post" action="/fileUpload" id="upload_form">
<input id="file_upload" type="file" name="fileImg" onchange="displayImage()"/>
<input type="button" value="上传图片" onclick="manualSubmit()"/>
form>
<img id="uploaded_images" src="" style="width: 200px; height: 300px;border: black 1px solid" alt=""/>
body>
<script type="text/javascript">
// 选择图片显示
function displayImage() {
// 获取点击的文本框
let file = document.getElementById("file_upload");
let imgUrl = window.URL.createObjectURL(file.files[0]);
let img = document.getElementById('uploaded_images');
img.setAttribute('src', imgUrl); // 修改img标签src属性值
}
function manualSubmit(){
let form = document.getElementById("upload_form");
//判断是否已选文件,要么提交,要么提示选择文件
if (document.getElementById("uploaded_images").getAttribute("src").length > 0) {
form.submit();
}else {
alert("请先选择上传的文件!");
}
}
script>
html>
package com.xccafe.imageupload.util;
import java.util.UUID;
/**
* 处理图片名称的工具类
* @author wyp
*/
public class FileNameUtils {
/**
* 根据文件全名获取后缀名
* @param fileName 文件名
* @return 后缀名字符串
*/
public static String getSuffix(String fileName){
return fileName.substring(fileName.lastIndexOf("."));
}
/**
* 更改文件名(UUID防止上传文件重名)
* @param fileName 原文件名
* @return uuid处理后的新文件名
*/
public static String getFileName(String fileName){
String uuid = UUID.randomUUID().toString().replace("-","");
return uuid + getSuffix(fileName);
}
}
package com.xccafe.imageupload.util;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
/**
* 处理图片属性的工具类
* @author wyp
*/
public class FileUtils {
/**
* 获取图片宽度
* @param multipartFile org.springframework.web.multipart.MultipartFile
* @return Integer宽度 or null
*/
public static Integer getImageWidth(MultipartFile multipartFile){
try {
BufferedImage bufferedImage = ImageIO.read(multipartFile.getInputStream());
return bufferedImage.getWidth();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 获取图片高度
* @param multipartFile org.springframework.web.multipart.MultipartFile
* @return Integer高度 or null
*/
public static Integer getImageHeight(MultipartFile multipartFile){
try {
BufferedImage bufferedImage = ImageIO.read(multipartFile.getInputStream());
return bufferedImage.getHeight();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
首先先创建一个图片的vo类
package com.xccafe.imageupload.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class ImageVo {
/**
* 0-正常 1-失败
*/
private Integer statusCode;
/**
* 图片地址
*/
private String url;
/**
* 图片宽度
*/
private Integer width;
/**
* 图片高度
*/
private Integer height;
/**
* 失败
* @return ImageVo
*/
public static ImageVo fail(){
return new ImageVo(1,null,null,null);
}
/**
* 成功
* @param url 图片地址
* @param width 图片宽度
* @param height 图片高度
* @return ImageVo
*/
public static ImageVo success(String url,Integer width,Integer height){
return new ImageVo(0,url,width,height);
}
}
UploadImagController.java
package com.xccafe.imageupload.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UploadImgController {
/**
* 显示图片上传页 url:http://localhost:8080/
* @return upload-image.html页面
*/
@RequestMapping("/")
public String index(){
return "upload-image";
}
}
启动服务访问地址http://localhost:8080/
,如下图:
选择文件后上传,会出现404,F12可以看到以下信息
接下来我们要实现图片上传的功能。
4.1 在此之前我们先配置一下图片上传的位置和允许上传的类型,resources目录下创建/properties/file_configuration.properties
文件,
# 文件要上传保存的位置
file.localDir=E:/image/images
# 文件支持的后缀名集合(以,分隔)
file.suffixList=.jpg,.png,.gif,.jpeg
4.2 业务层创建接口UploadImageService
和它的实现类UploadImageServiceImpl
。
UploadImgController.java中添加以下代码
@Resource
private UploadImgService uploadImgService;
/**
* 实现图片上传
* @param fileImg MultipartFile fileImg与前端表单中的name名一致
* @return ImageVo
* @throws IOException IOException
*/
@ResponseBody
@RequestMapping("/fileUpload")
public ImageVo uploadImg(MultipartFile fileImg) throws IOException {
return uploadImgService.uploadImg(fileImg);
}
4.3 接下来顺势实现uploadImgService.uploadImg(fileImg)
方法。
package com.xccafe.imageupload.service;
import com.xccafe.imageupload.vo.ImageVo;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
public interface UploadImgService {
/**
* 上传图片
* @param multipartFile MultipartFile
* @return ImageVo对象
*/
ImageVo uploadImg(MultipartFile multipartFile) throws IOException;
}
package com.xccafe.imageupload.service.impl;
import com.xccafe.imageupload.service.UploadImgService;
import com.xccafe.imageupload.util.FileNameUtils;
import com.xccafe.imageupload.util.FileUtils;
import com.xccafe.imageupload.vo.ImageVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
@Service
@PropertySource("classpath:/properties/file_configuration.properties")
public class UploadImgServiceImpl implements UploadImgService {
@Value("${file.localDir}")
private String localDir;
@Value("${file.suffixList}")
private String suffix;
@Override
public ImageVo uploadImg(MultipartFile multipartFile) throws IOException {
//获取原始图片名称
String originalFilename = multipartFile.getOriginalFilename();
originalFilename = Objects.requireNonNull(originalFilename).toLowerCase();
//获取图片类型
String suffixName = FileNameUtils.getSuffix(originalFilename);
List<String> strings = Arrays.asList(suffix.split(","));
//不包含规定的后缀名则直接返回失败
if (!strings.contains(suffixName)) {
return ImageVo.fail();
}
//创建日期目录--yyyy/MM/dd
String format = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
//File对象封装文件路径
File file = new File(localDir + "/" + format);
//如果目录不存在创建多级目录
if (!file.exists()) {
boolean mkdirs = file.mkdirs();
System.out.println("日期文件夹" + (mkdirs ? "创建成功" : "创建失败"));
}
//根据是否存在宽高判断是否为图片而不是恶意文件
Integer imageWidth = FileUtils.getImageWidth(multipartFile);
Integer imageHeight = FileUtils.getImageHeight(multipartFile);
//uuid--文件名
String fileName = FileNameUtils.getFileName(originalFilename);
//文件上传
File newFile = new File(file.getAbsolutePath()+"/"+fileName);
multipartFile.transferTo(newFile);
return ImageVo.success(newFile.getAbsolutePath(), imageWidth,imageHeight);
}
}
搞完收工!选择一张图片去测试一下
上传成功!!!