在SpringMVC 模式下使用ResponseEntity返回灵活定义Header的Gzip压缩文件流

        
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

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

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

        @RequestMapping("/handle")
	public ResponseEntity handle() throws IOException{
		logger.info("/test/handle.do ... ");
		
		URI location = URI.create("http://www.example.com");
		HttpHeaders headers= new  HttpHeaders();
		headers.setLocation(location);
		headers.set("binfile-md5", "my md5 value");//设置个性化的header
		headers.set("Content-Encoding", "gzip");
		headers.setContentDispositionFormData("attachment","my.txt");
		
		File file = new File("d:\\my.txt");// 读取文件
				
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		try (GZIPOutputStream gzos = new GZIPOutputStream(baos)) {
		    gzos.write(FileUtils.readFileToByteArray(file));
		    gzos.close();
		}catch(IOException ioException) {
			logger.error("GZIP occurs an error ... ");
			ioException.printStackTrace();
		}
		byte[] resultbyte = baos.toByteArray();
		
				
		return new ResponseEntity(resultbyte, headers, HttpStatus.CREATED); //返回压缩文件流
	}

在tomcat中启动项目,在postman输入地址 http://127.0.0.1:8088/datatask/test/handle.do

看到header如下:

Content-Disposition →form-data; name="attachment"; filename="my.txt"
Content-Encoding →gzip
Content-Length →508
Content-Type →application/octet-stream;charset=UTF-8
Date →Wed, 03 Jul 2019 10:16:37 GMT
Location →http://www.example.com
binfile-md5 →my md5 value

你可能感兴趣的:(企业应用,Java,Web开发)