在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<byte[]> 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<byte[]>(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安优小青和他的程序生活

我的文档对您有很大的帮助吗?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值