对象转成json,由于数据量过大压缩成.json.zip格式
发布时间:2024年01月05日
import cn.hutool.core.util.URLUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletResponse;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
private void downloadCompressedJsonData(WaveFormVo myObject, HttpServletResponse response) {
ObjectMapper objectMapper = new ObjectMapper();
String json = null;
try {
json = objectMapper.writeValueAsString(myObject);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename="+getDownloadFileName("数据.json.zip"));
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream)) {
ZipEntry zipEntry = new ZipEntry("data.json");
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write(json.getBytes());
zipOutputStream.closeEntry();
zipOutputStream.finish();
response.getOutputStream().write(byteArrayOutputStream.toByteArray());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String getDownloadFileName(String fileName) {
String finalFileName = fileName;
String userAgent = getUserAgent();
if(StringUtils.contains(userAgent, "MSIE")){
finalFileName = URLUtil.encode(fileName, Charset.forName("UTF-8"));
}else if(StringUtils.contains(userAgent, "Mozilla")){
finalFileName = URLUtil.encode(fileName, Charset.forName("UTF-8"));
}else{
finalFileName = URLUtil.encode(fileName, Charset.forName("UTF-8"));
}
return finalFileName;
}
public static String getUserAgent() {
return getRequestAttributes().getRequest().getHeader("USER-AGENT");
}
public static ServletRequestAttributes getRequestAttributes() {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
return (ServletRequestAttributes) attributes;
}
文章来源:https://blog.csdn.net/Mr_Dracy/article/details/135402026
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:chenni525@qq.com进行投诉反馈,一经查实,立即删除!