1. 程式人生 > 程式設計 >JAVA讀取檔案流,設定瀏覽器下載或直接預覽操作

JAVA讀取檔案流,設定瀏覽器下載或直接預覽操作

最近專案需要在瀏覽器中通過URL預覽圖片。但發現瀏覽器始終預設下載,而不是預覽。研究了一下,發現了問題:

// 設定response的Header,注意這句,如果開啟,預設瀏覽器會進行下載操作,如果註釋掉,瀏覽器會預設預覽。 response.addHeader("Content-Disposition","attachment;filename=" + FileUtil.getOriginalFilename(path));

然後需要注意:

response.setContentType(contentType);//不同的檔案型別,contentType不一樣,比如圖片一般是image/jpeg、image/png等

@RequestMapping(value = "getFile/{folder}/{fileName:.+}*",method = RequestMethod.GET)
 public void getFile(HttpServletResponse response,@PathVariable String folder,@PathVariable String fileName)
 {
  // 設定編碼
  response.setCharacterEncoding("UTF-8");
  try
  {
 
   String path = folder + "/" + fileName;
   boolean flag = ossClient.doesObjectExist(ossProperties.getBucket(),path);
 
   // 判斷檔案是否存在
   if (flag)
   {
    // 清空response
    response.reset();
    // 設定response的Header,注意這句,如果開啟,預設瀏覽器會進行下載操作,如果註釋掉,瀏覽器會預設預覽。
    // response.addHeader("Content-Disposition",// "attachment;filename=" + FileUtil.getOriginalFilename(path));
    // response.addHeader("Content-Length","" + buf.length);
   
    OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
    // ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
    OSSObject ossObject = ossClient.getObject(ossProperties.getBucket(),path);
 
    String contentType = ossObject.getObjectMetadata().getContentType();
    System.out.println(contentType);
    //注意contentType型別
    response.setContentType(contentType);
 
    byte[] buf = new byte[1024];
    InputStream in = ossObject.getObjectContent();
 
    int L;
    while ((L = in.read(buf)) != -1)
    {
     // if (buf.length != 0)
     // {
     toClient.write(buf,L);
     // }
    }
    in.close();
    // 寫完以後關閉檔案流
    toClient.flush();
    toClient.close();
    // response.getOutputStream().write(bos.toByteArray());
   }
   else
   {
    response.sendError(HttpServletResponse.SC_NOT_FOUND,"找不到相關資源");
   }
 
  }
  catch (IOException e)
  {
   e.printStackTrace();
  }
 }

補充知識:【Java檔案下載】如何讓瀏覽器直接下載後端返回的圖片,而不是直接開啟

預設情況下,瀏覽器設定是inline形式,對於伺服器返回的檔案,能開啟就開啟,不能開啟就自動下載。

Content-Disposition 設定

大多數情況下,後端都是實現一個檔案管理的功能,通過檔案的唯一標誌去獲取檔案流。後端都會讀取檔案,然後檔案的流寫入到response的輸出流,這樣就可以實現檔案的訪問了。

但是有些時候,實現下載功能,後端返回的是圖片,瀏覽器卻直接把圖片打開了?怎麼回事?

這就是Content-Disposition設定的問題,如下都是java示例:

設定為inline,如果瀏覽器支援該檔案型別的預覽,就會開啟,而不是下載:

response.setHeader("Content-Disposition","inline; filename=111.jpg");

設定為attachment,瀏覽器則直接進行下載,縱使他能夠預覽該型別的檔案。

response.setHeader("Content-Disposition","attachment; filename=111.jpg");

特別說明:Chrome不設定Content-Type也會自動開啟,如果是它可識別預覽的檔案。

示例程式碼

package cn.hanquan.controller;
import java.io.File;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class DemoDownload {
 @RequestMapping("download")
 public void download(String filename,HttpServletResponse res,HttpServletRequest req) throws IOException {
 // 設定響應流中檔案進行下載
 // attachment是以附件的形式下載,inline是瀏覽器開啟
 // bbb.txt是下載時顯示的檔名
// res.setHeader("Content-Disposition","attachment;filename=bbb.txt"); // 下載
 res.setHeader("Content-Disposition","inline;filename=bbb.txt"); // 瀏覽器開啟
 // 把二進位制流放入到響應體中
 ServletOutputStream os = res.getOutputStream();
 System.out.println("here download");
 String path = req.getServletContext().getRealPath("files");
 System.out.println("path is: " + path);
 System.out.println("fileName is: " + filename);
 File file = new File(path,filename);
 byte[] bytes = FileUtils.readFileToByteArray(file);
 os.write(bytes);
 os.flush();
 os.close();
 }
}

瀏覽器直接開啟效果

JAVA讀取檔案流,設定瀏覽器下載或直接預覽操作

下載效果

JAVA讀取檔案流,設定瀏覽器下載或直接預覽操作

以上這篇JAVA讀取檔案流,設定瀏覽器下載或直接預覽操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。