HttpServletResponse和 ResponseEntity下載文件預覽圖片

直接上菜,然後在點評一波:


import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;


@RestController
@RequestMapping(value = "/test")
public class KeyController {

    /**
     * ResponseEntity圖片預覽
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/responseEntityView")
    public ResponseEntity<byte[]> responseEntityView() throws Exception {
        File file = new File("E:\\圖片\\bpic4828.jpg");
        InputStream inputStream = new FileInputStream(file);
        byte[] bytes = null;
        bytes = readInputStream(inputStream);

        HttpHeaders httpHeaders = new HttpHeaders();
        // 不是用緩存
        httpHeaders.setCacheControl(CacheControl.noCache());
        httpHeaders.setPragma("no-cache");
        httpHeaders.setExpires(0L);
        httpHeaders.setContentType(MediaType.IMAGE_JPEG);
        ResponseEntity responseEntity = new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
        return responseEntity;
    }

    /**
     * ResponseEntity文件下載Post請求
     * (如果不會參數不多就最好使用get,post請求不會解碼文件名,如果不編碼中文就會成一個_,沒有中文用那個都可以)
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/responseEntityDownloadPost")
    public ResponseEntity<byte[]> responseEntityDownloadPost() throws Exception {
        File file = new File("C:\\Users\\Administrator\\Desktop\\tt\\小兒喜.zip");
        InputStream inputStream = new FileInputStream(file);
        byte[] bytes = null;
        bytes = readInputStream(inputStream);
        String fileName = URLEncoder.encode(file.getName(), "UTF-8");

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachment", fileName);
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity responseEntity = new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
        return responseEntity;
    }

    /**
     * ResponseEntity文件下載Get請求
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/responseEntityDownloadGet")
    public ResponseEntity<byte[]> responseEntityDownloadGet() throws Exception {
        File file = new File("C:\\Users\\Administrator\\Desktop\\tt\\小兒喜.zip");
        InputStream inputStream = new FileInputStream(file);
        byte[] bytes = null;
        bytes = readInputStream(inputStream);
        String fileName = URLEncoder.encode(file.getName(), "UTF-8");

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachment", fileName);
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity responseEntity = new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
        return responseEntity;
    }

    /**
     * ResponseEntity文件下載Get請求PostPost請求不會自動解碼,所以使用get請求轉一下就沒有問題了
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/responseEntityDownloadGetByPost")
    public ResponseEntity<byte[]> responseEntityDownloadGetByPost() throws Exception {
        ResponseEntity<byte[]> responseEntity = this.responseEntityDownloadPost();
        return responseEntity;
    }

    /**
     * HttpServletResponse圖片預覽
     *
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/httpServletResponseView")
    public String httpServletResponseView(HttpServletResponse response) throws Exception {
        File file = new File("E:\\圖片\\bpic4828.jpg");
        InputStream inputStream = new FileInputStream(file);
        byte[] bytes = null;
        OutputStream outputStream = response.getOutputStream();
        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
        // 不使用緩存
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("expires", -1);
        response.setHeader("Content-Disposition", "inline");
        readInputStreamToOutStream(inputStream, outputStream);
        return null;
    }


    /**
     * HttpServletResponse文件下載Post請求
     *
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping("/httpServletResponseDownloadPost")
    public String httpServletResponseDownloadPost(HttpServletResponse response) throws Exception {
        File file = new File("C:\\Users\\Administrator\\Desktop\\tt\\小兒喜.zip");
        InputStream inputStream = new FileInputStream(file);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setCharacterEncoding("UTF-8");
        OutputStream outputStream = response.getOutputStream();
        String fileName = URLEncoder.encode(file.getName(), "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        readInputStreamToOutStream(inputStream, outputStream);
        return null;
    }

    /**
     * HttpServletResponse文件下載Get請求
     *
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/httpServletResponseDownloadGet")
    public String httpServletResponseDownloadGet(HttpServletResponse response) throws Exception {
        File file = new File("C:\\Users\\Administrator\\Desktop\\tt\\小兒喜.zip");
        InputStream inputStream = new FileInputStream(file);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setCharacterEncoding("UTF-8");
        OutputStream outputStream = response.getOutputStream();
        String fileName = URLEncoder.encode(file.getName(), "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        readInputStreamToOutStream(inputStream, outputStream);
        return null;
    }

    /**
     * HttpServletResponse文件下載Get請求通過Post生成數據
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/httpServletResponseDownloadGetByPost")
    public String httpServletResponseDownloadGetByPost(HttpServletResponse response) throws Exception {
        this.httpServletResponseDownloadPost(response);
        return null;
    }


    /**
     * 輸入流裝成字節數組
     *
     * @param inStream
     * @return
     * @throws Exception
     */
    private byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * 輸入流寫進輸出流
     *
     * @param inStream
     * @param outStream
     * @throws Exception
     */
    private void readInputStreamToOutStream(InputStream inStream, OutputStream outStream) throws Exception {
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        outStream.close();
    }

}

 

結論:

1、HttpServletResponse 和 ResponseEntity的使用主要看個人了,如果使用Spring的項目就可以選擇使用ResponseEntity,沒有用Spring就可以直接使用HttpServletResponse。

2、不管用那個來下載文件,如果這個文件名是中文就要編碼(不編碼中文會變成_,沒有中文就可以不編碼的哦),但是編碼也有一個問題,post請求不會自動解碼,目前我是沒有找到解決的方法(如果您有就可以寫在評論區),get就會自動解碼,所以有時候後臺直接可以使用post請求(需要組裝後臺其他服務的多個參數的時候),前端獲取的使用用get轉一下就可以了。建議儘量使用get請求。

3、ResponseEntity其實可以看做是把HttpServletResponse封裝了,但是功能比HttpServletResponse多,推介使用。

4、contentType的類型如果沒有具體的類型就可以使用"application/octet-stream(MediaType.APPLICATION_OCTET_STREAM)",如果有具體類型建議使用具體類型。

5、如有不對請在評論區進行評論,謝謝。

《………………………………………………菜鳥起飛中,請各位走過路過的多多指教……………………………………》

                                                                       

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章