springBoot優雅返回圖片/網頁到瀏覽器


一、普通spring mvc返回圖片或網頁到瀏覽器

@Controller
@RequestMapping(value = "/image")
public class ImageController {
    @RequestMapping(value = "/get")
    @ResponseBody
    public void getImage(HttpServletResponse response) throws IOException {
        File file = new File("D:/test.jpg");
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        
        response.setContentType("image/jpeg");
        OutputStream out = response.getOutputStream();
       out.write(result);
       out.flush();
       //關閉響應輸出流
       out.close();
       
    }
}

 

 

 

二、spring boot

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
 
@Controller
@RequestMapping(value = "/image")
public class ImageController {
    @RequestMapping(value = "/get",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getImage() throws IOException {
        File file = new File("D:/test.jpg");
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        return bytes;
    }
}

如果是網頁的話,

produces = MediaType.TEXT_HTML


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM