1.场景
产品需要实现一个上传图片的功能,后端选择使用文件服务器保存图片,返回一个url给前端展示图片。
由于前端访问后端接口使用的是https协议,而后端返回图片的url使用的是http(使用的文件服务器),前端不用访问该url地址,会出现如下错误
2.解决方案
后端使用文件流形式返回图片给前端,前提是后端需要有接口可以把图片下载下来。
代码如下:
@ApiOperation(value = "获取文件预览url", notes = "获取文件预览url")
@PostMapping(value = "/getBrowseUrl")
public void getBrowseUrl(@ApiParam(value = "文件id", required = true) @RequestParam String fileId, HttpServletResponse response) {
byte[] fileBytes = fileSupport.downloadFile(fileId);
if (fileBytes == null || fileBytes.length == 0) {
throw new BaseException("文件系统中不存在该文件");
}
response.setContentType("image/" + "png");
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Methods","'GET, POST, OPTIONS'");
response.setHeader("Access-Control-Allow-Headers","'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'");
try {
IoUtil.write(response.getOutputStream(),true,fileBytes);
} catch (IOException e) {
log.error("文件预览异常:"+fileId,e);
throw new BaseException("文件预览失败");
}
}