springboot实现查看图片,播放语音功能
这块的需求是通过调用接口,在浏览器上查看图片和播放语音片段的功能
以下是接口的实现代码
//在配置文件application.properties里面给图片路径设值或者使用默认值
@Value("${resource.image.path:/appsystems/miniprogram/transport/image/}")
private String imagePath;
/**
* 获取图片资源
* */
@GetMapping(
value = "/get-image-with-media-type/{type}/{fileName:.+}",
produces = {MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_JPEG_VALUE}
)
//上面的produces 是告诉浏览器,返回的资源格式是jpg和png
public byte[] getImageWithMediaType(@PathVariable("type") String type,@PathVariable("fileName") String fileName) throws IOException {
//此处是读取resources下的图片资源,相对路径
// InputStream in = this.getClass().getClassLoader().getResourceAsStream("static/"+fileName);
//传入图片文件的绝对路径
//type 是对图片的文件夹分类
File file = new File(imagePath+ type+ File.separator + fileName);
InputStream in = new FileInputStream(file);
//IOUtils 来自org.apache.commons.io包
return IOUtils.toByteArray(in);
}
在浏览器访问此接口,即可看到硬盘中的图片。
此接口地址放在标签的src属性中,可显示图片
//在配置文件里给语音路径设值或者使用默认值
@Value("${resource.voice.path:/appsystems/miniprogram/transport/voice/}")
private String EXTERNAL_FILE_PATH;
/**
* 获取音频资源
* */
@GetMapping("/getAudio/{fileName:.+}")
public void getAudioResource(HttpServletRequest request, HttpServletResponse response,
@PathVariable("fileName") String fileName) throws IOException {
File file = new File(EXTERNAL_FILE_PATH + fileName);
if (file .exists()) {
//get the mimetype
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
if (mimeType == null) {
//unknown mimetype so set the mimetype to application/octet-stream
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
/**
* In a regular HTTP response, the Content-Disposition response header is a
* header indicating if the content is expected to be displayed inline in the
* browser, that is, as a Web page or as part of a Web page, or as an
* attachment, that is downloaded and saved locally.
*
*/
/**
* Here we have mentioned it to show inline
*/
response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() + "\""));
//Here we have mentioned it to show as attachment
//response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + file.getName() + "\""));
response.setContentLength((int) file.length());
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
FileCopyUtils.copy(inputStream, response.getOutputStream());
}
}
浏览器访问上面的接口,即可读取到硬盘中的音频文件。
此接口地址放在类似于innerAudioContext的src属性中,可实现语音播放。
声明:代码非原创,系在网络中自行摸索找到而后优化的。