LoginSignup
51
47

More than 5 years have passed since last update.

ブラウザにファイルを強制ダウンロードさせるContent-Type

Last updated at Posted at 2012-12-12

ブラウザでリンクを開くと自動的にファイルダウンロードを開始させる方法。レスポンスヘッダのContent-Typeにapplication/force-downloadを指定しておくと、ファイル形式に関係なくダウンロードを開始させられる。

例えば、 http://[ドメイン]/downloadpdf にアクセスが来るとPDFファイルをダウンロードさせたい時のコード。

PDFファイルを返すController
@RequestMapping(value = "/downloadpdf", method = RequestMethod.GET)
public void downloadPdf(HttpServletResponse response) throws Exception {

     response.setContentType("application/pdf");

     InputStream in = new FileInputStream(
          new File("/Users/horimislime/Desktop/sample.pdf"));
     OutputStream out = response.getOutputStream();

     IOUtils.copy(in, out); //PDFファイルをレスポンスで返す
}

ChromeなどPDFのインライン表示をサポートしているブラウザでは、/downloadpdfを開くとファイルをダウンロードせずブラウザ上に表示してしまう。以下のようにContent-Typeを指定するとダウンロードを強制させられる。

 
response.setContentType("application/force-download");
51
47
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
51
47