response.setContentType 不起作用

功能:
想做一個從本地獲取圖片,在瀏覽器顯示圖片而不是下載圖片的功能

代碼:

//工具類
public static void picUtils(HttpServletResponse response, String path) {
        response.setContentType("text/html; charset=UTF-8");
        response.setContentType("image/jpeg");
        InputStream in = null;
        OutputStream os = null;
        try {
            //讀取本地圖片輸入流
            in = new FileInputStream(path);
            os = response.getOutputStream();
            IOUtils.copy(in, os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
controller:
 //  國旗
    @GetMapping("flags/common/100x100/{pictureId}.jpg")
    public void getCountryPic(@PathVariable String pictureId, HttpServletResponse response) {
        String path = userHome + "/gfx/flags/common/100x100/" + pictureId + ".jpg";
        picUtils(response, path);
    }

問題:

 response.setContentType("text/html; charset=UTF-8");
 response.setContentType("image/jpeg");

儘管設置了返回類型爲jpeg圖片類型,但是這兩行代碼不起作用
漫長的尋找原因過程……
最後,
controller參數加入:HttpServletRequest request 解決問題

public void getCountryPic(@PathVariable String pictureId, HttpServletResponse response, HttpServletRequest request) 
        String path = userHome + "/gfx/flags/common/100x100/" + pictureId + ".jpg";
        picUtils(response, path);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章