Skip to content

Instantly share code, notes, and snippets.

@muthuishere
Last active March 25, 2022 16:31
Show Gist options
  • Save muthuishere/786bc4cfc4eb4ec6397a9af96d49f3fa to your computer and use it in GitHub Desktop.
Save muthuishere/786bc4cfc4eb4ec6397a9af96d49f3fa to your computer and use it in GitHub Desktop.
Compress Backend & Decompress in Frontend
function App() {
const [data, setData] = useState('Loading...');
useEffect(() => {
getCompressedData().then((result) => {
setData(result);
}).catch((e) => {
setData(e.toString());
});
}, []);
return (
<div className="App">
<header className="App-header">
<p>
Received <br/>{data}
</p>
</header>
</div>
);
}
export default App;
public static byte[] compress(String str)throws IOException {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip=new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
return out.toByteArray();
}
async function getCompressedData() {
const axiosResponse = await axios.post('http://localhost:8080/compress',
{
data:"Deemwar Monads and abstractions"
},
{
responseType: 'blob'
}
);
return await unzipBlobToString(axiosResponse.data);
}
async function readZippedBlob(input) {
const reader = new FileReader();
reader.readAsArrayBuffer(input);
return new Promise((resolve, reject) => {
reader.onload = () => {
console.log(reader.result);
const data = reader.result;
const unzipped = pako.inflate(data, {to: 'string'});
resolve(unzipped);
};
});
}
//Install pako
async function getData() {
const raw = await axios.post('http://localhost:8080/reports',
{
data:"Deemwar Monads and abstractions"
},
{
responseType: 'blob'
});
let input = raw.data;
return await readZippedBlob(input);
}
// Usage
// const result = await getData() ;
@RequestMapping(value = "compress", method = RequestMethod.POST
, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
)
public @ResponseBody byte[] compressApi(@RequestBody String request) {
try {
return compress(request);
} catch (Exception e) {
throw new ResponseStatusException(
HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage(), e);
}
}
async function unzipBlobToString(input) {
const reader = new FileReader();
const result= new Promise((resolve, reject) => {
reader.onload = () => {
const data = reader.result;
const unzipped = pako.inflate(data, {to: 'string'});
resolve(unzipped);
};
});
reader.readAsArrayBuffer(input);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment