以Spring Boot的方式显示图片或下载文件到浏览器
请求例子:http://localhost:8080/image/1564550185144.jpeg
示例代码:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.io.File;
import java.io.IOException;
@Configuration
public class ImageShow implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
File directory = new File("image");
String path = null;
try {
path = directory.getCanonicalPath();
}catch (IOException e){
e.printStackTrace();
}
registry.addResourceHandler("/image/**").addResourceLocations("file:"+path+"/");
}
}
运行结果:
显示图片
下载文件