简体   繁体   中英

Sending wave file in HttpResponse makes it corrupt

I am trying to read a wav file from the resources of my Java Spring project and then convert the file to a byte array and write it to outputstream of HttpResponse. When I receive the file from my web application it is broken with garbage data.

Here is the code in my servlet:

response.setContentType("audio/wav");
response.setHeader("Content-Disposition", "attachment;filename=audio-qrcode-"+"hellosine"+".wav");
response.setHeader("Pragma", "private");
response.setHeader("Cache-Control", "private, must-revalidate");
response.setHeader("Accept-Ranges", "bytes")

URL helloSineWav = QRcodeController.class.getClassLoader().getResource("hellosine.wav");
byte[] audioBytes = IOUtils.toByteArray(helloSineWav.openStream());
response.setContentLength(audioBytes.length);
ServletOutputStream outStream = response.getOutputStream();
outStream.write( audioBytes );
outStream.flush();
outStream.close();

Another way I tried to approach the solution was:

ServletOutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
    out.write(buf, 0, len);
}
is.close();
out.close();

Both approach work but give me a corrupted audio file at the other end. I am not exactly sure why this is happening. Is it something to do with the header?

I figured out the problem. It wasn't really related to httpResponse or any of this. I added the wave file to the Java Project and packaged a war file from it. But when I deploy the project and the resource file gets unpacked it changes the size of the file from the original and introduces some garbage information. I am currently looking into why that happens. But as far as this question is concerned, when I replaced the wave file with the correct size one it works. Sorry for bothering you guys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM