需求是这样的,有个接口,调用这个接口直接就能显示pdf文档,或者直接查看图片什么的,那么设计的时候接口的返回值就是void ,正常就是输出流配置contentype直接显示,但是我还得请求其他nginx代理方式的图片或者文件http的地址,然后最后将http返回的数据转换称byte[]输出,如愿以偿达到效果。
但是突然说这个接口啊,需要加一个没有权限就要提示的中文字样,我想着返回值是void怎么搞,三思以后机智的想出将String提示转换byte[]数组,实践以后是可以的,但是输出是乱码,乱码,还是乱码,然后怎么搜也搜不到这个byte输出数组转换中文,后来搜索response输出中文给我带来了灵感,直接将response.setContentType("text/plain; charset=utf-8"),设置成文本方式输出并UTF-8就好了啊。
以下是代码,这样就能显示提示信息了
public byte[] picturefileProxy(HttpServletResponse response){
byte[] bytes =null;
response.setContentType("text/plain; charset=utf-8");
String info = "该资源地址没有被加入申请!";
try {
bytes = info.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return bytes;
}
controller输出byte[]
public void picturefileProxy(@PathVariable(name = "resourceIdenti") String resourceIdenti,
HttpServletResponse response) {
byte[] bytes = proxyService.picturefileProxy(resourceIdenti, response);
log.info("ContentType的格式:{}", response.getContentType());
OutputStream os = null;
try {
os = response.getOutputStream();
os.write(bytes);
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
界面展示,审核通过界面直接展示pdf文档
审核未通过,或者没有加入申请就需要提示语了,然后看下效果
是不是处理的非常完美,都不用前端去管就直接像输出控制台那样输出就行了。
希望可以帮到你!