我想用spring在浏览器中显示pdf。 我的问题是浏览器下载文件而不是显示它。 这是我的代码:
@RequestMapping(value="/getpdf1", method=RequestMethod.GET)
public ResponseEntity<byte[]> getPDF1() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "pdf1.pdf";
headers.add("content-disposition", "inline;filename=" + filename);
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(pdf1Bytes, headers, HttpStatus.OK);
return response;
}
我期待着你的回答! 感谢
答案 0 :(得分:11)
你差不多完成了。只需删除
headers.setContentDispositionFormData(filename, filename);
来自您的代码块的。将multipart / form-data发布到服务器时应该使用它。
答案 1 :(得分:4)
内容处置,以控制下载或在浏览器中查看
在浏览器中查看
trait Foo[F, T] {
def aa(foo: F): List[T]
def maybe(foo: F): Option[T]
def instance(aa: List[T], maybe: Option[T]): F
}
class Bar(val aa: List[String], val maybe: Option[String]) {
override def toString = s"Bar($aa, $maybe)"
}
object Bar {
implicit val barFoo = new Foo[Bar, String] {
def aa(foo: Bar): List[String] = foo.aa
def maybe(foo: Bar): Option[String] = foo.maybe
def instance(aa: List[String], maybe:Option[String]):Bar = new Bar(aa, maybe)
}
}
implicit class FooOps[A, T](fooable:A)(implicit foo:Foo[A, T]) {
def copy(aa: List[T] = foo.aa(fooable), maybe: Option[T] = foo.maybe(fooable)) = {
foo.instance(aa, maybe)
}
}
val r = new Bar(List(""), Option("")).copy(aa = List("asd"))
println(r)
下载
public function rosters(){
return $this->belongsToMany(Roster::class)
->withPivot('number','position')
->using(Membership::class)
->as("membership");
}
答案 2 :(得分:2)
下面的代码片段将帮助您在浏览器上显示文件
@GetMapping(value = "/terms-conditions")
public ResponseEntity<InputStreamResource> getTermsConditions() {
String filePath = "/path/to/file/";
String fileName = "fileName.pdf";
File file = new File(filePath+fileName);
HttpHeaders headers = new HttpHeaders();
headers.add("content-disposition", "inline;filename=" +fileName);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/pdf"))
.body(resource);
}