返回文件流/文件预览

package com.example.replace.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @description:
 * @author: Sandul
 * @create: 2021-05-07 09:47
 **/
@Controller
@RequestMapping("/test")
public class TestController {

	@GetMapping("/pdf")
	public void Outpust(HttpServletResponse response) throws IOException {
		//使用这个返回pdf文件类型的文件流(浏览器中直接预览)
		//response.setContentType(MediaType.APPLICATION_PDF_VALUE); 
		//使用这个直接返回流,在浏览器中直接下载
		response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
		//
		response.setCharacterEncoding(StandardCharsets.UTF_8.name());
		OutputStream outputStream = null;
		InputStream inputStream = null;
		long start = System.currentTimeMillis();
		try {
			outputStream = response.getOutputStream();
			inputStream = new BufferedInputStream(new FileInputStream("D:\\JAVA\\javaCode\\replace\\src\\main\\resources\\123.pdf"));
//			inputStream = new ByteArrayInputStream("hello world".getBytes());
			int len=0;
			byte[] bytes = new byte[4096];
			while ((len=inputStream.read(bytes))!=-1){
				outputStream.write(bytes,0,len);
				outputStream.flush();
				System.out.println("-----------------"+len);
			}
//			IOUtils.copy(inputStream, outputStream);
			long end = System.currentTimeMillis();
			System.out.println(end-start);
		}catch (Exception e){
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(outputStream);
			IOUtils.closeQuietly(inputStream);
		}
	}

}

上一篇:Java学习笔记之IO(二):InputStream输入字节流


下一篇:Java:InputStream、OutputStream(一)——概述