spring - 在响应对象中返回文件

时间:2017-12-03 18:02:03

标签: java spring spring-mvc spring-boot file-io

我试图在Spring框架中将图像作为响应返回, 它可以很好地实现这样:

@GetMapping(value = "/{photo}.{suf}")
public @ResponseBody byte[] getImage(@PathVariable("photo") String photo,@PathVariable("suf") String suf) throws IOException{
    InputStream in = FileUtils.openInputStream(new File("src/main/resources/static/" + photo + "." +suf));
    return IOUtils.toByteArray(in);
}

但是当我尝试在响应对象中返回图像文件时,我得到一个org.springframework.web.HttpMediaTypeNotAcceptableException异常:

@GetMapping(value = "/{photo}.{suf}")
public @ResponseBody ResponseObject getImage(@PathVariable("photo") String photo,@PathVariable("suf") String suf) throws IOException{
    InputStream in = FileUtils.openInputStream(new File("src/main/resources/static/" + photo + "." +suf));
    return new ResponseObject(IOUtils.toByteArray(in),1);
}

这是我的ResponseObject实现:

public class ResponseObject {
private Object object;
private int status;
public ResponseObject(Object object,int status){
    this.object = object;
    this.status = status;
}
public Object getObject() {
    return this.object;
}

public void setObject(Object object) {
    this.object = object;
}

public int getStatus() {
    return status;
}

public void setStatus(int status) {
    this.status = status;
}

}

有谁知道为什么会这样?

0 个答案:

没有答案