Java Web中上传图片以及显示图片的方法
环境需求
创建一个spring boot starter项目
- 打开你熟悉的开发工具,创建一个spring boot starter项目,只需要在pom.xml中加入spring web依赖即可
- 如果你创建的是maven项目,那么可以上官网,根据提示自动生成一个符合要求的pom.xml文件,替换掉原来的pom.xml文件即可
- pom.xml的内容如下(artifactId和groupId等请根据自己的情况设置)
<?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.5.3</version>
<relativePath/>
</parent>
<groupId>kmhc</groupId>
<artifactId>ImageUpload</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ImageUpload</name>
<description>Image Upload Demo</description>
<properties>
<java.version>1.8</java.version>
</properties>
<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>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
编写获取图片的逻辑
- 先不着急写上传图片的逻辑,先写获取图片的逻辑,看看图片是否能够根据想想中的一样获取,具体代码如下(包名请根据情况自行决定)
package kmhc.api;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ImageController {
private static final String BASE_PATH = "D:\\workspace\\java\\ImageUpload\\src\\media";
@GetMapping(path = "/image/{filename}", produces = { MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_JPEG_VALUE,
MediaType.IMAGE_PNG_VALUE })
public BufferedImage getImage(@PathVariable("filename") String filename) throws IOException {
File file = new File(BASE_PATH, filename);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
BufferedImage image = ImageIO.read(in);
in.close();
return image;
} else {
return null;
}
}
}
- 除了上面的代码以外,还需要提供BufferedImage的解析器,代码如下
package kmhc.config;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.BufferedImageHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ImageConfig implements WebMvcConfigurer {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new BufferedImageHttpMessageConverter());
}
}
编写上传图片的逻辑
- 上传图片的逻辑要稍微复杂一点,考虑到代码的鲁棒性,需要用条件判断语句做处理,完整代码如下
package kmhc.api;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import javax.imageio.ImageIO;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class ImageController {
private static final String BASE_PATH = "D:\\workspace\\java\\ImageUpload\\src\\media";
@GetMapping(path = "/image/{filename}", produces = { MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_JPEG_VALUE,
MediaType.IMAGE_PNG_VALUE })
public BufferedImage getImage(@PathVariable("filename") String filename) throws IOException {
File file = new File(BASE_PATH, filename);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
BufferedImage image = ImageIO.read(in);
in.close();
return image;
} else {
return null;
}
}
@PostMapping(value = "/image", produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE })
public void uploadImage(MultipartFile file) throws IOException {
File folder = new File(BASE_PATH);
if (!folder.exists()) {
folder.mkdirs();
}
String oldName = file.getOriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
file.transferTo(new File(folder, newName));
}
}
- 打开postman,尝试上传一张图片,注意请求格式必须是post请求(这个要看具体情况,也有可能是patch),并且body格式是form-data
![上传一张图片](https://i-blog.csdnimg.cn/blog_migrate/95146845db0b3547bea3620b84e484f9.png)
![上传图片成功](https://i-blog.csdnimg.cn/blog_migrate/e7ceeb4ccbb211bf8a781dbc0d9cb3cb.png)
- 可以看到图片上传成功,并且名字也被改成了UUID了
问题点
- 如果提示404,那么有可能是服务没有重新启动的原因,需要手动重新服务才能生效
- 建议加入spring boot devtools依赖,可以热启动,代码保存后就重启服务,这一部分请自行上官网加入依赖